看起来编译器接受不同的语法来初始化模板中的静态。
template <typename T> struct TBase { static const int i; static const int j; }; // compile: gcc + clang + visual + icc template <> const int TBase<double>::i=1; // compile: vc + icc // failed gcc, gcc -fpermissive, clang const int TBase<double>::j=2;标准是否接受没有template<>的语法,即使它现在显然不可移植?
编辑:使用此代码在vc ++ TBase<double>::i==1和TBase<double>::j==2完全类似于没有模板的代码。
struct noTemplate { static const int i; static const int j; }; const int noTemplate::i=1; const int noTemplate::j=2;gcc和clang似乎强制使用template<>来初始化这个静态,我不明白为什么编译器需要这些信息。
It looks like compilers accept different syntax to initialization of static in template.
template <typename T> struct TBase { static const int i; static const int j; }; // compile: gcc + clang + visual + icc template <> const int TBase<double>::i=1; // compile: vc + icc // failed gcc, gcc -fpermissive, clang const int TBase<double>::j=2;Is the syntax without template<> accepted by the standard even if it's obviously not portable at the moment ?
edit: With this code on vc++ TBase<double>::i==1 and TBase<double>::j==2 exactly like the code without template.
struct noTemplate { static const int i; static const int j; }; const int noTemplate::i=1; const int noTemplate::j=2;gcc and clang seems to enforce the use of template<> to initialize this static, I don't see why compiler need this information.
最满意答案
这两种语法都有效,但它们意味着不同的东西。 template<>的语法用于声明或定义隐式或显式实例化的成员:
template<class T> struct X { static int const i; }; template<> int const X<char>::i = 1; // Define member of an implicit instantiation template struct X<long>; template<> int const X<long>::i = 2; // Define member of an explicit instantiation不带template<>的语法用于定义特化的成员:
template<> struct X<float> { static int const j; }; // Class template specialization int const X<float>::j = 3;The two syntaxes are both valid, but they mean different things. The syntax with template<> is used to declare or define a member of an implicit or explicit instantiation:
template<class T> struct X { static int const i; }; template<> int const X<char>::i = 1; // Define member of an implicit instantiation template struct X<long>; template<> int const X<long>::i = 2; // Define member of an explicit instantiationThe syntax without template<> is used to define a member of a specialization:
template<> struct X<float> { static int const j; }; // Class template specialization int const X<float>::j = 3;更多推荐
发布评论