如何强制初始化静态成员?

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

问题描述

限时送ChatGPT账号..

考虑这个示例代码:

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_)没有任何实例BarFoo(没有实例,所以没有构造器技巧)并且 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;

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

上一篇:使用不同的 enable_if 条件选择成员函数 下一篇:为什么编译器不能从默认参数推导出模板类型?

相关文章

最新文章