問(wèn)題描述
考慮這個(gè)示例代碼:
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
的具體實(shí)例化后立即被初始化,我有 Bar
.這個(gè)問(wèn)題(以及最后的標(biāo)準(zhǔn)引用)解釋得很清楚,為什么沒(méi)有發(fā)生.
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.
[...] 特別是,靜態(tài)數(shù)據(jù)成員的初始化(和任何相關(guān)的副作用)不會(huì)發(fā)生,除非靜態(tài)數(shù)據(jù)成員本身以需要靜態(tài)數(shù)據(jù)成員定義的方式使用存在.
[...] 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.
有什么方法可以強(qiáng)制 dummy
被初始化(有效地調(diào)用register_
)沒(méi)有任何實(shí)例Bar
或 Foo
(沒(méi)有實(shí)例,所以沒(méi)有構(gòu)造器技巧)并且 Foo
的用戶不需要以某種方式顯式聲明成員?不需要派生類(lèi)做任何事情的額外 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.
編輯:找到一種對(duì)派生類(lèi)影響最小的方法:>
struct Bar
: Foo<Bar>
{ // vvvvvvvvvvvv
static char const get_dummy() { (void)dummy; return 42; }
};
盡管如此,我仍然希望派生類(lèi)不必這樣做.:|
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;
這篇關(guān)于如何強(qiáng)制初始化靜態(tài)成員?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!