如何強制自動初始化靜態成員
C 中的靜態成員不會自動初始化,除非以需要其使用方式的方式使用它們定義存在。這種行為有時會很不方便,特別是當您想要在靜態成員初始化期間執行副作用時。
考慮以下範例:
<code class="cpp">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; } };</code>
在這個範例中,您希望 dummy 為一旦有 Foo 的特定實例化(Bar 就有了),它就會被初始化。然而,由於靜態成員的延遲初始化行為,情況並非如此。
要在沒有任何Bar 或Foo 實例的情況下強制初始化虛擬,您可以使用以下技術之一:
<code class="cpp">template<class D> struct Bar : Foo<Bar> { static char const get_dummy() { return (void)dummy; return 42; } };</code>
<code class="cpp">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;</code>
<code class="cpp">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;</code>
這些技術可讓您強制初始化靜態成員,而不需要使用者乾預或修改衍生類別。使用的具體技術將取決於您的特定要求和編碼風格偏好。
以上是如何在 C 中自動強制初始化靜態成員?的詳細內容。更多資訊請關注PHP中文網其他相關文章!