【问题标题】:Explicit template instantiation example显式模板实例化示例
【发布时间】:2021-11-25 19:29:12
【问题描述】:

我目前正在看一本书,它有以下示例:

//ch4_4_class_template_explicit.cpp
#include <iostream>

using namespace std;
template < typename T > //line A
  struct A {
    A(T init): val(init) {}
    virtual T foo();
    T val;
  }; //line B
//line C
template < class T > //T in this line is template parameter
  T A < T > ::foo() { //the 1st T refers to function return type,
    //the T in <> specifies that this function's template
    //parameter is also the class template parameter
    return val;
  } //line D
extern template struct A < int > ; //line E
#if 0 //line F
int A < int > ::foo() {
  return val + 1;
}
#endif //line G
int main(void) {
  A < double > x(5);
  A < int > y(5);
  cout << "fD=" << x.foo() << ",fI=" << y.foo() << endl;
  return 0; //output: fD=5,fI=6
}

谁能给我解释一下是什么意思

extern template struct A < int > ;

foo() 的第二个定义是否以及为什么? 我了解显式模板实例化是什么以及为什么它有时很有用,但我并不十分清楚 extern 的使用。

书中对这一行有如下解释:

使用 extern 关键字可以防止该函数模板的隐式实例化(参见 下一节了解更多详细信息)。

所以extern 阻止我们执行以下操作?:

auto obj = A<int>;

然后第二个定义否定外部?这个例子我实在看不懂。

编辑 1:添加注释代码。

编辑 2: 我几乎可以肯定我的理解是正确的。不过谢谢你的回答。

书上的解释:
在前面的代码块中,我们在 A 行和 B 行之间定义了一个类模板,然后 我们从 C 行到 D 行实现了它的成员函数 foo()。接下来,我们显式地 在 E 行将它实例化为 int 类型。由于 F 行和行之间的代码块 G 被注释掉(这意味着 foo() 没有对应的定义 这个显式的 int 类型实例化),我们有一个链接错误。为了解决这个问题,我们需要更换 #if 0 和 #if 1 在 F 行。

【问题讨论】:

标签: c++ templates metaprogramming


【解决方案1】:

也许这有助于你理解。

来自 C++ 20(13.9.2 显式实例化)

2 显式实例化的语法是:

explicit-instantiation:
    externopt template declaration

显式实例化有两种形式:显式实例化 实例化定义和显式实例化声明。一个 显式实例化声明以 extern 关键字开头。

所以这一行

extern template struct A < int > ;

是类特化struct A&lt;int&gt;的显式实例化声明。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-02
    • 2021-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多