如何强制静态成员初始化? [英] How to force a static member to be initialized?

查看:153
本文介绍了如何强制静态成员初始化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑此示例代码:

template<class D>
char register_(){
    return D::get_dummy(); // static function
}

template<class D>
struct Foo{
    static char const dummy;
};

template<class D>
char const Foo<D>::dummy = register_<D>();

struct Bar
    : Foo<Bar>
{
    static char const get_dummy() { return 42; }
};

另请参阅Ideone 。)

我希望 dummy Foo ,我使用 Bar 这个问题(以及最后的标准报价)解释得很清楚,为什么这不会发生。

I'd expect dummy to get initialized as soon as there is a concrete instantiation of Foo, which I have with Bar. This question (and the standard quote at the end) explained pretty clear, why that's not happening.


[...]特别是,静态数据的初始化(和任何相关的副作用)成员不会发生,除非静态数据成员本身以需要静态数据成员的定义的方式使用。

[...] 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.

是否有任何方法可以强制 dummy 进行初始化(有效地调用 register _ 没有 Bar Foo 的任何实例(没有实例,因此没有构造函数欺骗) Foo 的用户需要以某种方式显式声明成员?不需要派生类执行任何操作的额外Cookie。

Is there any way to force dummy to be initialized (effectively calling register_) without any instance of Bar or Foo (no instances, so no constructor trickery) and without the user of Foo needing to explicitly state the member in some way? Extra cookies for not needing the derived class to do anything.

编辑找到一种对派生类影响最小的方式

struct Bar
    : Foo<Bar>
{   //                              vvvvvvvvvvvv
    static char const get_dummy() { (void)dummy; return 42; }
};

但是,我仍然希望派生类不必这样做。 :|

Though, I'd still like the derived class not having to do that. :|

推荐答案

请考虑:

template<typename T, T> struct value { };

template<typename T>
struct HasStatics {
  static int a; // we force this to be initialized
  typedef value<int&, a> value_user;
};

template<typename T>
int HasStatics<T>::a = /* whatever side-effect you want */ 0;

也可以不引入任何成员:

It's also possible without introducing any member:

template<typename T, T> struct var { enum { value }; };
typedef char user;

template<typename T>
struct HasStatics {
  static int a; // we force this to be initialized
  static int b; // and this

  // hope you like the syntax!
  user :var<int&, a>::value,
       :var<int&, b>::value;
};

template<typename T>
int HasStatics<T>::a = /* whatever side-effect you want */ 0;

template<typename T>
int HasStatics<T>::b = /* whatever side-effect you want */ 0;

这篇关于如何强制静态成员初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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