Forced Static Member Initialization
A common question in C programming involves forcing the initialization of static members without creating instances of the defining class or requiring the user to explicitly reference the member.
Consider the following code:
<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>
In this example, we expect dummy to be initialized upon instantiation of the concrete class Bar. However, as the standard states, static member initialization only occurs when the member is used in a way that requires its definition.
To force initialization, several techniques can be employed:
Using a Dummy Value Type
<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>
This approach introduces a dummy type value that relies on the address of the static member a. By using value_user in another context, we indirectly access a and trigger its initialization.
Using Indirect Member References
<code class="cpp">template<typename T> struct HasStatics { static int a; // we force this to be initialized static int b; // and this 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>
This technique utilizes anonymous members to access the addresses of static members. By referencing these members via the var type, the compiler is forced to initialize a and b.
The above is the detailed content of How to Force Initialization of Static Members in C Without Explicitly Referencing Them?. For more information, please follow other related articles on the PHP Chinese website!