首頁  >  文章  >  後端開發  >  如何在 C 中自動強制初始化靜態成員?

如何在 C 中自動強制初始化靜態成員?

Susan Sarandon
Susan Sarandon原創
2024-10-28 05:04:02605瀏覽

How to Force Initialization of Static Members Automatically in C  ?

如何強制自動初始化靜態成員

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中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn