Initialization Procedure for Static Template Elements

I have a question related to the previous question posted here Static Field Initialization Procedure Suppose I have the following structure with two static members xand y(the templates 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 xand yabove main(), and you can see what ydepends on x, so it is better to initialize first x.

My questions:

  • At the time of initialization types xand yare not yet known, so when they do initialized? Static members are actually initialized after instantiating the template Foo<double> foo;in main()?
  • , x y , .. y, x ( , ) , .. - , y x. ( )? g++ 4.8 clang++ OS X.

!

+2
1

, Foo<double>::x , Foo<double>::y .

3.6.2/2:

:

  • ...

  • , , , .

, - ; - . .

, :

double tmp = 1.1;

template <typename T>
T Foo<T>::x = tmp;

template <typename T>
T Foo<T>::y = 2.0 * Foo<T>::x;

"" - Foo<double>::y 2.2, 0.0 ( , tmp ).

+3

Source: https://habr.com/ru/post/1617404/


All Articles