Static Objects in Class and Function Templates


A template class that is generated from a class template containing a static member has its own copy of that static. Consider the following example.

template<class T>
class test
{
 public:
  static T tStatic;
};
 
test<int> templateInteger;   // tStatic is of type integer and is static member of test<int>.
test<double> templateNumber; // tStatic is of type double and is static member of test<double>.

int test<int>::tStatic = 0;         // separate definition of static member required.
double test<double>::tStatic = 0.0; // separate definition of static member required.

A function that is generated from a function template and which declares a local static variable has its own copy of that static. Consider the following example.

template<class T>
void f(T& tReference)
{
 static T tStatic;
 tStatic = tReference;
}
 
void main()
{
 int i=0;
 double n=0;
 f(i);      // generate and call: void f(int& tReference) - tStatic of type int.
 f(n);      // generate and call: void f(double& tReference) - tStatic of type double.
}