In a given file if I have,
struct A { static int a; };
struct B { static int b; };
int A::a;
int B::b;
Then, I can always expect that A::a gets initialized before B::b. Now for the same file, take the template case,
template<typename T>
struct X { static T t; };
template<typename T>
T X<T>::t;
Suppose, X is instantiated with A and B and its static member is used arbitrarily somewhere in the code as, X<A>::t and X<B>::t, then what should be the order for initialization of template static member X<T>::t; ? Is it well defined ?
As long as the templates only have one definition (e.g. you only have one translation unit), it’s well-defined. The static members are initialized in the order that the template specializations are instantiated in contexts that require the definition of the static data member. From §14.7.1/1 [temp.inst] of the C++03 standard (emphasis mine):
§14.7.1/7 also states:
However, things get more complicated when you have multiple translation units that define the template. §3.2/5 [basic.def.odr] states:
Note that the standard doesn’t specify which definition is taken as the single definition, only that some definition is chosen. So, if multiple translation units instantiate the templates in different orders, there’s no guarantee what the order of initialization will be.