Question

gcc 4.5.1, SuSE Linux i686

Suppose we have following code:

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

In this case we won't have any output in the stdout. Compiler won't generate code to initialize float and double specialization of class A.

But.. if we'll change initializations like this:

template<> B<float> A<float>::static_var = B<float>();
template<> B<double> A<double>::static_var = B<double>();

the compiler will generate such code and we'll have double "B()" in the output.

Can somebody help me with understanding of such behaviour?

Was it helpful?

Solution

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 is C++11 feature, so in C++03 you can use only

template<> X Q<int>::x = ...;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top