Static member initialization in a class template

C++TemplatesStatic

C++ Problem Overview


I'd like to do this:

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

but I can't since something_relevant is not of integral type. It doesn't depend on T, but existing code depends on it being a static member of S.

Since S is template, I cannot put the definition inside a compiled file. How do I solve this problem ?

C++ Solutions


Solution 1 - C++

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.

Solution 2 - C++

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

Solution 3 - C++

This will work

template <typename T>
 struct S
 {

     static double something_relevant;
 };

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlexandre C.View Question on Stackoverflow
Solution 1 - C++sbiView Answer on Stackoverflow
Solution 2 - C++xaxxonView Answer on Stackoverflow
Solution 3 - C++Prasoon SauravView Answer on Stackoverflow