gcc 4.5.1, SuSE Linux i686
假设我们有以下代码:
template<typename realT> class B
{
public:
B() {std::cout << "B()" << std::endl;}
};
template<typename realT> class A
{
public:
static B<realT> static_var;
};
template<typename realT> B<realT> A<realT>::static_var;
template<> B<float> A<float>::static_var;
template<> B<double> A<double>::static_var;
int main()
{
A<float> test;
return 0;
}
在这种情况下,我们不会在标准输出中有任何输出。编译器不会生成代码来初始化类 A 的 float 和 double 特化。
但是..如果我们像这样改变初始化:
template<> B<float> A<float>::static_var = B<float>();
template<> B<double> A<double>::static_var = B<double>();
编译器将生成这样的代码,我们将在输出中有两个“B()”。
有人可以帮助我理解这种行为吗?
最佳答案
n3337 14.7.3/13
An explicit specialization of a static data member of a template is a definition if the declaration includes an initializer; otherwise, it is a declaration. [ Note: The definition of a static data member of a template that requires default initialization must use a braced-init-list:
template<> X Q<int>::x; // declaration template<> X Q<int>::x (); // error: declares a function template<> X Q<int>::x { };// definition
— end note ]
braced-init-list
是 C++11
特性,所以在 C++03
中你只能使用
template<> X Q<int>::x = ...;
关于C++静态模板成员初始化问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12384783/