member template variable specializing
Asked Answered
K

1

6

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?

Karli answered 8/9, 2016 at 14:7 Comment(3)
Can you please include the actual error you get?Gasworks
@NathanOliver: Done ;)Karli
Well those are less than helpful. I was hoping there would be something in there to make the title more searchable but alas, the compiler is not helping here.Gasworks
W
8

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"

Wallas answered 8/9, 2016 at 14:14 Comment(5)
That is... amazingly silly (the cause, not the answer).Serrato
I've understand where is the problem because I've done the same error two hours ago :(Wallas
An example of how poor code formatting actually can lead to bugs. At least in this case the compiler caught it.Pussy
Verily, one of the runner-ups behind the most-vexing parse...Monteria
@Monteria - I'm bad in labelling but... yes, something similarWallas

© 2022 - 2024 — McMap. All rights reserved.