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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…