問題描述
考慮這個示例代碼:
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;
這篇關于如何強制初始化靜態成員?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!