外部模板不能用于gcc
extern template does not work for gcc?
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模板而不包含实例化,链接器会产生错误。
不,不一定。只有当您实际使用模板时才会出现问题。您使用的是定义为该模板的静态成员的编译时常量,但它在编译时被该常量的值所替换。在替换之后,不再使用模板,因此不需要定义模板。
相关文章:
- 为什么我的 SFINAE 表达式不再适用于 GCC 8.2?
- 适用于 gcc 4.8 的任何正则表达式库
- 流输入运算符导致分段错误与 clang 但适用于 gcc
- enable_if的模板专用化在 Clang 中失败,适用于 GCC
- 函数指针数组的类模板参数推导适用于 clang,但不适用于 gcc
- 可变参数模板作为模板参数:演绎适用于 GCC,但不适用于 Clang
- 何时将-g标志用于GCC
- 从Visual Studio解决方案生成生成生成文件(用于GCC)
- -m32 选项不适用于 gcc,但适用于 g++
- 库与 Clang 合作,但不适用于 GCC
- 即使启用了 C++11,静态成员初始化也不适用于 GCC
- 为什么void_t<>检测习惯用语不适用于 gcc-4.9?
- 宏调用中的 #ifdef 适用于 GCC,但不适用于 MSVC
- 静态表生成适用于 GCC,但不适用于 clang;被叮当窃听
- 用于提升program_options的自定义验证器不适用于 GCC,适用于 MSVC
- 模板的类型定义包括char[][] - 适用于VS2008,但不适用于gcc
- 模板专用化适用于 gcc,但不适用于 Visual Studio 10
- c ++ 11 参数包在 Apple LLVM 7.0.0 中存在错误行为,但适用于 GCC-5.1
- 此代码有效吗?适用于 gcc,不要与 clang 合作
- 使用enable_if选择特征-适用于clang,但不适用于gcc