外部模板不能用于gcc

extern template does not work for gcc?

本文关键字:用于 gcc 不能 外部      更新时间:2023-10-16

c++ 11引入了一个名为'extern template'的特性,它表示模板实例存在于其他翻译单元中。(我说的对吗?)

这个(http://www.youtube.com/watch?v=3annCCTx35o)讲座还告诉我们,如果你指定了extern模板而不包含实例化,链接器将产生错误。(视频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不支持外部模板?

<标题> 更新

我已经尝试了一个非内联函数的类,和外部模板工作如预期!

#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;
}

上面的源代码没有注释行是不能构建的。谢谢大家!

如果你指定了extern模板而不包含实例化,链接器会产生错误。

不,不一定。只有当您实际使用模板时才会出现问题。您使用的是定义为该模板的静态成员的编译时常量,但它在编译时被该常量的值所替换。在替换之后,不再使用模板,因此不需要定义模板。