C++11 引入了一个名为“extern template”的功能,该功能指示模板实例存在于其他翻译单元中。(我说得对吗?)
这个( http://www.youtube.com/watch?v=3annCCTx35o )讲座还告诉我们,如果您指定外部模板并且不包含实例化,链接器将产生错误。(视频中的2:25左右)
所以,我尝试构建下一个代码:
#include <iostream>
template<class T>
struct Foo
{
static constexpr int type_size = sizeof(T);
};
extern template struct Foo<int>;
int main()
{
std::cout<< Foo<int>::type_size << std::endl;
return 0;
}
我预计构建会失败,因为该文件不包含显式实例化或专门化,但 gcc 只是构建它,结果运行良好。
我错过了什么?或者,我误解了什么吗?或者说,gcc对extern模板支持不好吗?
更新
我尝试了一个带有非内联函数的类,并且外部模板按预期工作!
#include <iostream>
template<class T>
struct Foo
{
static void print(T t);
};
template<class T>
void Foo<T>::print(T t) { std::cout << t << std::endl; }
extern template struct Foo<int>;
// template struct Foo<int>;
int main()
{
Foo<int>::print(1);
return 0;
}
如果没有注释行,则不会构建上述源代码。 谢谢大家!
最佳答案
if you specify extern template and don't include instantiation, the linker will produce error.
不,不一定。只有当您实际使用该模板时才会出现问题。您正在使用定义为该模板的静态成员的编译时常量,但该常量在编译时被常量的值替换。并且在替换之后,不再使用该模板,因此不需要定义该模板。
关于c++ - extern 模板不适用于 gcc?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23633255/