If a template class definition contains a static member variable that depends on the template type, I'm unsure of what the reliable behavior should be?
In my case it is desirable to place the definition of that static member in the same .h file as the class definition, since
MyClass<int>
and one for all MyClass<double>
, etc.I can be most brief by saying that the code listed at this link behaves exactly as I want when compiled with gcc 4.3. Is this behavior according to the C++ Standard so that I can rely on it when using other compilers?
That link is not my code, but a counter example posted by CodeMedic to the discussion here. I've found several other debates like this one but nothing I consider conclusive.
I think the linker is consolidating the multiple definitions found ( in the example a.o
and b.o
).
Is this the required/reliable linker behavior?
From N3290, 14.6:
A [...] static data member of a class template shall be defined in every translation unit in which it is implicitly instantiated [...], unless the corresponding specialization is explicitly instantiated [...] .
Typically, you put the static member definition in the header file, along with the template class definition:
template <typename T>
class Foo
{
static int n; // declaration
};
template <typename T> int Foo<T>::n; // definition
To expand on the concession: If you plan on using explicit instantiations in your code, like:
template <> int Foo<int>::n = 12;
then you must not put the templated definition in the header if Foo<int>
is also used in other TUs other than the one containing the explicit instantiation, since you'd then get multiple definitions.
However, if you do need to set an initial value for all possible parameters without using explicit instantiation, you have to put that in the header, e.g. with TMP:
// in the header
template <typename T> int Foo<T>::n = GetInitialValue<T>::value; // definition + initialization