Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 777
Klaus Avatar asked Sep 08 '16 14:09

Klaus


People also ask

What is a template specialization?

The act of creating a new definition of a function, class, or member of a class from a template declaration and one or more template arguments is called template instantiation. The definition created from a template instantiation is called a specialization.

What is the difference between Typename and class in template?

There is no difference between using <typename T> OR <class T> ; i.e. it is a convention used by C++ programmers.

Can a member function be a template?

Member functions can be function templates in several contexts. All functions of class templates are generic but aren't referred to as member templates or member function templates. If these member functions take their own template arguments, they're considered to be member function templates.

Are template specializations inline?

An explicit specialization of a function template is inline only if it is declared with the inline specifier (or defined as deleted), it doesn't matter if the primary template is inline.


1 Answers

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"

like image 179
max66 Avatar answered Oct 21 '22 02:10

max66