C Static Member Initialization within Nested Template Functions
Static member initialization can be achieved through nested helper structs, especially in non-templated classes. However, this approach may encounter issues when the enclosing class is parametrized by a template. Specifically, if the helper object is not accessed in the main code, the nested initialization class may not instantiate.
Consider the following simplified example, which illustrates the initialization of a vector:
<code class="cpp">struct A { struct InitHelper { InitHelper() { A::mA = "Hello, I'm A."; } }; static std::string mA; static InitHelper mInit; static const std::string& getA(){ return mA; } }; std::string A::mA; A::InitHelper A::mInit; template<class T> struct B { struct InitHelper { InitHelper() { B<T>::mB = "Hello, I'm B."; } }; static std::string mB; static InitHelper mInit; static const std::string& getB() { return mB; } static InitHelper& getHelper(){ return mInit; } }; template<class T> std::string B<T>::mB; template<class T> typename B<T>::InitHelper B<T>::mInit;</code>
When compiled with g 4.4.1, several observations are made:
This behavior stems from the compiler's interpretation of the ISO/IEC C 2003 standard (14.7.1). The standard stipulates that:
"Unless a member of a class template or a member template has been explicitly instantiated or explicitly specialized, the specialization of the member is implicitly instantiated when the specialization is referenced in a context that requires the member definition to exist; 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."
This explains why, in the given example, the static members are not initialized until they are accessed through the getB() or getHelper() methods. Explicitly instantiating the class template or member template in the main function would force their initialization at that point. However, for scenarios where direct access is not feasible, the standard does not specify an elegant workaround for initializing static members within nested template functions.
The above is the detailed content of How to Initialize Static Members in Nested Template Functions in C ?. For more information, please follow other related articles on the PHP Chinese website!