Defining Static Data Member in a Class Template
A need often arises to define a static data member within a class template. However, the traditional approach of defining the member within the class declaration is not feasible as it must be initialized outside the class definition due to non-integral data types. This poses a challenge, especially when the class is a template, prohibiting the definition from being placed in a separate compiled file.
To resolve this issue, a technique involves defining the static data member within the header file but initializing it outside in a separate definition. Here's an example:
template <typename T> struct S { static double something_relevant; }; template <typename T> double S<T>::something_relevant = 1.5;
In this approach, the static data member something_relevant is initially declared within the class template definition. Then, its initialization is performed outside in a separate definition, where it can be any non-integral data type. Since the definition is part of the template, the compiler ensures it is defined only once, avoiding multiple definitions.
The above is the detailed content of How to Define and Initialize Static Data Members in C Class Templates?. For more information, please follow other related articles on the PHP Chinese website!