Static member initialization in a class template

Alexandre C. picture Alexandre C. · Jul 12, 2010 · Viewed 85.6k times · Source

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 ?

Answer

sbi picture sbi · Jul 12, 2010

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.