gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 17:10:58 25 4
gpt4 key购买 nike

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

//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 explicitinstantiation definition and an explicit instantiation declaration. Anexplicit instantiation declaration begins with the extern keyword.

所以这条线

extern template struct A < int > ;

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

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com