c++templatesc++14template-specializationtemplate-variables

member template variable specializing


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

class B
{   
    public:
        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 ( error messages with gcc 6.1):

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

Fails with:

main.cpp:49:23: error: parse error in template argument list
 template <> double B::var<double>= 1.123;
                       ^~~~~~~~~~~~~~~~~~
main.cpp:49:23: error: template argument 1 is invalid
main.cpp:49:23: error: template-id 'var<<expression error> >' for 'B::var' does not match any template declaration
main.cpp:38:22: note: candidate is: template<class X> T B::var<T>
             static X var;

template <> double B::var=1.123;

Fails with

   template <> double B::var=1.123;
                       ^~~
main.cpp:38:22: note: does not match member template declaration here
             static X var;

What is the correct syntax here?


Solution

  • 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"