c++ - 显式模板实例化示例

标签 c++ templates metaprogramming

我正在看一本书,书中有以下例子:

//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>;

第二个定义否定了 extern?我真的无法理解这个例子。

编辑 1:添加注释代码。

编辑 2: 我几乎可以肯定我的理解是正确的。但感谢您的回答。

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

最佳答案

也许这有助于您理解。

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

2 The syntax for explicit instantiation is:

explicit-instantiation:
    externopt template declaration

There are two forms of explicit instantiation: an explicit instantiation definition and an explicit instantiation declaration. An explicit instantiation declaration begins with the extern keyword.

所以这条线

extern template struct A < int > ;

是类特化的显式实例化声明 struct A<int> .

关于c++ - 显式模板实例化示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69451793/

相关文章:

c++ - 将 boost-di 与配置文件和共享库一起使用

c++ - 对于模板类 Foo 方法的参数, "Foo&"和 "Foo<T>&"是否相同?

c++ - 为什么 C++ POD 结构没有默认散列?

c++ - C++ 元编程中的蹦床

javascript - 身份保持膜代理的用例是什么?

c++ - 在 OpenCV/C++ 中通过(扩展)卡尔曼滤波器实现数据融合

c++ - 如何在不等待的情况下使用 future ?

c++ - 使用doxygen在GitLab项目上自动生成C++文档

c++ - 模板类复制构造函数

c++ - 用于重复代码的 C/C++ 宏