Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static member initialization in a class template

People also ask

How are static members declared within a template class?

Each class template instantiation has its own copy of any static data members. The static declaration can be of template argument type or of any defined type. The statement template T K::x defines the static member of class K , while the statement in the main() function assigns a value to the data member for K <int> .

How do you initialize a static member of a class?

For the static variables, we have to initialize them after defining the class. To initialize we have to use the class name then scope resolution operator (::), then the variable name. Now we can assign some value. The following code will illustrate the of static member initializing technique.

What happens when there is static member in a template class function?

The static member is declared or defined inside the template< … > class { … } block. If it is declared but not defined, then there must be another declaration which provides the definition of the member.

Where should you initialize a static data member?

The initializer for a static data member is in the scope of the class declaring the member. A static data member can be of any type except for void or void qualified with const or volatile .


Just define it in the header:

template <typename T>
struct S
{
    static double something_relevant;
};

template <typename T>
double S<T>::something_relevant = 1.5;

Since it is part of a template, as with all templates the compiler will make sure it's only defined once.


Since C++17, you can now declare the static member to be inline, which will define the variable in the class definition:

template <typename T>
struct S
{
    ...
    static inline double something_relevant = 1.5;
};

live: https://godbolt.org/g/bgSw1u


This will work

template <typename T>
 struct S
 {

     static double something_relevant;
 };

 template<typename T>
 double S<T>::something_relevant=1.5;