I have a question related to a previous question posted here Static field initialization order
Suppose I have the following struct, with 2 static members x
and y
(templated types themselves)
#include <iostream>
using namespace std;
template <typename T>
struct Foo
{
static T x;
static T y;
Foo()
{
cout << "x = " << x << endl;
cout << "y = " << y << endl;
}
};
template <typename T>
T Foo<T>::x = 1.1f;
template <typename T>
T Foo<T>::y = 2.0 * Foo<T>::x;
int main()
{
Foo<double> foo;
}
Output:
x = 1.1
y = 2.2
I initialize x
and y
above main()
, and you can see that y
depends on x
, so it better be that x
is initialized first.
My questions:
- At the point of initialization, the types of
x
andy
are still unknown, so when are they really initialized? Are the static members actually initialized after the template instantiationFoo<double> foo;
inmain()
? - And if yes, the order of declarations of
x
andy
seems not to matter, i.e. I can first declarey
thenx
(both in the struct and in the static initialization) and still get the correct output, i.e. the compiler knows somehow thaty
is dependent onx
. Is this a well defined behaviour (i.e. standard-compliant)? I use g++ 4.8 and clang++ on OS X.
Thanks!