How to force a static member to be initialized?(如何强制初始化静态成员?)
问题描述
考虑这个示例代码:
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;
这篇关于如何强制初始化静态成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何强制初始化静态成员?


基础教程推荐
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01