Is a static member variable initialized in a template class if no static scale is used?

Is a static member variable initialized in a template class if no static member is used? I use it to register a type.

template<class T>
class A
{
    static bool d;
};

template<class T> bool A<T>::d = [](){regist<A<T>>(); return true;}();

int main()
{
   A<int> a;
   return 0;
}

I found a way to test it. It prints 1, except 2. Regist () is not called abd, the static member is not initialized. My testing is done on the VC110 compiler. And I also test it online

#include <iostream>
using namespace std;

int i = 1;

template<class T>
void regist()
{
    ++i;
}

template<class T>
class A
{
    static bool d;
};

template<class T> bool A<T>::d = [](){regist<A<T>>(); return true;}();

int main()
{
    A<int> a;
    cout << i << endl;
    return 0;
}
+3
source share
2 answers

Yes, the launch of this sample program is initialized, but only because it is forced to exist.

template <class T>                                                                 
struct A                                                                           
{                                                                                  
    static int b;                                                                  
};                                                                                 
template <class T> int A<T>::b = 10;                                               
#include <iostream>                                                                
using namespace std;                                                               
int main() {                                                                       
    cout << A<int>::b << endl;                                                     
    return 0;                                                                      
}   

,

[: , , . [: run_chain running , . - ] - ]

, .

(14.7.2) (14.7.3), , , . , , , -, -; . - , , , ; , ( ) , , ,

, , , . , , , , ( )

+2

++ 14 , 14.7.1 2, ( ):

- , , , ; , ( ) , , .

8, :

- .

, , , 2 :

template<> bool A<int>::d = [](){regist<A<int>>(); return true;}();
+2

All Articles