我目前正在閱讀一本書,它有以下示例:
//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:我幾乎可以肯定我的理解是正確的。不過謝謝你的回答。
Explanation from the book:
In the preceding code block, we defined a class template between lines A and B, and then
we implemented its member function, foo(), from lines C to line D. Next, we explicitly
instantiated it for the int type at line E. Since the code block between lines F and line
G is commented out (which means that there is no corresponding definition of foo() for
this explicit int type instantiation), we have a linkage error. To fix this, we need to replace
#if 0 with #if 1 at line F.
uj5u.com熱心網友回復:
也許這有助于你理解。
來自 C 20(13.9.2 顯式實體化)
2 顯式實體化的語法是:
explicit-instantiation:
externopt template declaration
顯式實體化有兩種形式:顯式實體化定義和顯式實體化宣告。顯式實體化宣告以 extern 關鍵字開始。
所以這一行
extern template struct A < int > ;
是類專業化的顯式實體化宣告struct A<int>。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/312613.html
