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?

3
  • 1
    Can you please include the actual error you get? Sep 8, 2016 at 14:41
  • @NathanOliver: Done ;)
    – Klaus
    Sep 8, 2016 at 14:56
  • 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. Sep 8, 2016 at 15:07

1 Answer 1

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"

5
  • 2
    That is... amazingly silly (the cause, not the answer). Sep 8, 2016 at 14:16
  • I've understand where is the problem because I've done the same error two hours ago :(
    – max66
    Sep 8, 2016 at 14:19
  • 1
    An example of how poor code formatting actually can lead to bugs. At least in this case the compiler caught it. Sep 8, 2016 at 15:00
  • Verily, one of the runner-ups behind the most-vexing parse...
    – einpoklum
    Oct 26, 2018 at 18:20
  • @einpoklum - I'm bad in labelling but... yes, something similar
    – max66
    Oct 26, 2018 at 18:22

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.