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
- I want the class to be general for many template data types that I don't currently
know. - I want only one instance of the static member to be shared
throughout my program for each given template type. ( one for allMyClass<int>
and one for allMyClass<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?
Best Answer
From N3290, 14.6:
Typically, you put the static member definition in the header file, along with the template class definition:
To expand on the concession: If you plan on using explicit instantiations in your code, like:
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: