Klaus Klaus - 1 year ago 58
C++ Question

member template variable specializing

A class can contain a member template variable which must be static:

class B
template <typename X>
static X var;

B() { std::cout << "Create B " << __PRETTY_FUNCTION__ << std::endl; }

template <typename T>
void Print() { std::cout << "Value is " << var<T> << std::endl; }

It must as all static members be declared outside the class scope:

The following compiles and works as expected:

template<typename T> T B::var=9; // makes only sense for int,float,double...

But how to specialize such a var like the following non working code:

template <> double B::var<double>=1.123; // fails
template <> double B::var=1.123; //fails

What is the correct syntax here?

Answer Source

I suppose you should add a space

template <> double B::var<double> = 1.123;
                                 ^ here

Otherwise (if I'm not wrong) >=1.123 is confused with "equal or greather than 1.123"