c++ Static data members and class templates:

The static data members are declared inside class and defined outside of class and this applies on any class or class template.

template <typename T> class K
{
public:
      static T a; // declaration
};
template <typename T> T K<T> ::a;   // definition

int main()
{
      K<int>::a = 10; // assignment
}

Every class template instantiation has its own copy of any static data members.

#include<iostream>
using namespace std;

template < typename T > class Base
{
  public:
  static int a;
  Base ()
  {
    ++a;
  }
};

template < typename T > int Base < T >::a = 0;

int
main ()
{
  Base < int >base1;
  Base < int >base2;
  Base < float >base3;
  cout << Base < int >::a << endl;
  cout << Base < float >::a << endl;
  return 0;
}

After compilation when we will run the program, we will get output:

2
1

Note: Here when we instantiate Base<int> base1, the variable a is getting increase by 1 in its constructor.  Again second instantiation  of Base<int> base2 calls its constructor and now a is increase by 1. Hence cout<<Base<int>::a will be 2. while when we instantiate Base<float>base3, a separate copy of static variable a is maintained in Base class template.

Hence the two instances one Base<int> and another Base<float> will have the two separate copy of static member a.

c++ Static data members and function templates:

Each function template instance will have separate copy of local static variable.



Related Contents to follow