Home > Article > Backend Development > Can You Force Initialization of Static Members in Template Classes Without Instantiation?
How to Explicitly Initialize Static Members
Question:
In C , static members of a template class are only initialized when explicitly used within a concrete instantiation. Is there a way to force their initialization without creating an instance or requiring the user to specify the member directly?
Answer:
Yes, it is possible to force the initialization of a static member by employing one of the following techniques:
Using a Wrapper 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>
Using a Syntactic Trick:
<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>
Both techniques force the initialization of the static members by introducing a dependency that triggers the evaluation of the member's definition. Note that the second technique involves unconventional syntax and may not be suitable for all cases.
The above is the detailed content of Can You Force Initialization of Static Members in Template Classes Without Instantiation?. For more information, please follow other related articles on the PHP Chinese website!