First, let's look at the Code. There are two types of static data members: the first one is not dependent on template type parameters, and the second one is dependent on template type parameters.
template <typename T> class TestTemStatic{ public: static int knownTypeVar; static T unKnownTypeVar;};
So how to initialize it?
There are two initialization methods for the first method:
Template <> int testtemstatic <int/* any other type */>: knowntypevar = 2; // defines the T type and num, t can be any other specific type. Template <typename T> int testtemstatic <t>: knowntypevar = 50; // standardized definition. You do not need to know the T type when defining num.
If you want to give a specific value to a static member of a specific type T, use the first method. If you want to have a common value for any type of T, use the second method.
The two types of initialization can coexist. If a specific type of T has a custom definition, the specific definition prevails. And the specific definition of T type cannot be repeated in different (CPP) Implementation files.
//a.cpptemplate <typename T> int TestTemStatic<T>::knownTypeVar=50;//b.cpptemplate <typename T> int TestTemStatic<T>::knownTypeVar=60;
The standardized definition can be repeated in different (CPP) Implementation files or different values can be assigned. The linker is responsible for selecting the unique definition. Which one to choose depends on the specific compilation sequence.
Therefore, the standardized definition can be placed in the header file, and the specific definition can be placed in a unique CPP file.
There is only one Initialization Method in Example 2:
template <> float TestTemStatic<float>::unKnownTypeVar=4.0f;
Since the definition of unknowtypevar depends on the type of the template parameter t, the type of T must be given when unknowntypevar is defined. Similarly, the custom definitions of specific types of t cannot be repeated in different (CPP) Implementation files.
The author's level is limited. I usually don't have much contact with Templates. If you have any mistakes, please correct me.