C++静态模板成员初始化问题

标签 c++ gcc initialization static-members static-initialization

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-listC++11 特性,所以在 C++03 中你只能使用

template<> X Q<int>::x = ...;

关于C++静态模板成员初始化问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12384783/

相关文章:

linux - 编写修改 gcc c 编译器的 bash 脚本

c++ - static const的C++容器初始化列表导致栈溢出

java - 如何初始化静态 map ?

c++ - 如果 C++ 模板从未被引用,它是否会使用内存?

c++ - 如何处理WASAPI流中的声音数据 block 而不将它们写入文件?

c++ - GCC 4.8 中 C++11 thread_local 变量的性能损失是多少?

java - 二维数组初始化错误

C++ 参数包,受限于单一类型的实例?

c++ - 无类型的连续内存容器

c - 当指定 -g 时,gcc 是否定义任何内容?