为什么除非使用静态模板字段初始化? [英] Why aren't static template fields initialized unless used?

查看:161
本文介绍了为什么除非使用静态模板字段初始化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

(静态初始化/模板实例化)问题

尝试强制静态对象初始化





编辑:有一个副本,但我会离开这,因为我个人很难找到它。此外,这里的答案帮助我:



http:// stackoverflow。 com / a / 2852234/673730

假设有以下类:

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();

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

I would have assumed that when I specialize A, the static field x would get initialized. However, the following:

A<int> a;
//no output

不会导致调用 foo 。如果我尝试访问成员,行为是预期的:

doesn't result in a call to foo. If I try to access the member, the behavior is as expected:

A<int> a;
bool b = a.x;
//output: here

编辑:我如何确保<$

How can I make sure A::x is initialized without accessing it?

推荐答案

这个想法是参考(14.7.1.2):

This think is the reference(14.7.1.2) :

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

Unless a member of a class template or a member template has been explicitly instantiated or explicitly specialized, the specialization of the member is implicitly instantiated when the specialization is referenced in a context that requires the member definition to exist; in particular, the initialization (and any associated side-effects) of a static data member does not occur unless the static data member is itself used in a way that requires the definition of the static data member to exist.

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

这篇关于为什么除非使用静态模板字段初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆