除非使用,否则为什么不初始化静态模板字段?

Luc*_*ore 6 c++ templates

可能重复:(
静态初始化/模板实例化)工厂模式
试图强制静态对象初始化的问题

编辑:有一个副本,但我会留下这个,因为我个人很难找到它.另外这里有帮助我的答案:

/sf/answers/199656411/

假设以下课程:

template<class X>
struct A
{
   static bool x;
   static bool foo()
   {
      cout << "here";
      return true;
   }
};

template<class X>
bool A<X>::x = A<X>::foo();
Run Code Online (Sandbox Code Playgroud)

我会假设当我专注时A,静态字段x将被初始化.但是,以下内容:

A<int> a;
//no output
Run Code Online (Sandbox Code Playgroud)

不会导致打电话foo.如果我尝试访问该成员,行为是预期的:

A<int> a;
bool b = a.x;
//output: here
Run Code Online (Sandbox Code Playgroud)

编辑:如何A::x在不访问它的情况下确保初始化?

Ker*_* SB 12

如果模板由于被实例化而被隐式专门化,则仅实例化那些实际引用的成员.

将其与显式类模板实例化(template struct A<int>;)进行对比,后者实例化并为所有成员创建代码.(您也可以单独实例化特定成员:template bool A<int>::x;.)


Man*_*niP 1

这个认为是参考(14.7.1.2):

除非类模板或成员模板的成员已显式实例化或显式特化,否则当在需要成员定义存在的上下文中引用特化时,会隐式实例化该成员的特化;特别是,静态数据成员的初始化(以及任何相关的副作用)不会发生,除非静态数据成员本身以需要静态数据成员的定义存在的方式使用。

template<class X, bool y>
struct A
{
    static cosnt bool x = y;
    static bool foo()
    {
       cout << "here";
       return true;
    }
 };
Run Code Online (Sandbox Code Playgroud)