Thursday, August 4, 2016

Static Members and Variables


Each template class or function generated from a template has its own copies of any static variables or members.


Each instantiation of a function template has it's own copy of any static variables defined within the scope of the function.



Static members are defined as follows.

////TTT.h
#include <iostream>
using namespace std;

template<typename T>
class X
{
public:
  static T s;
};

template<typename T> T X<T>::s = 0;
template<> int X<int>::s = 3;
template<> char* X<char*>::s = "Hello";

int main()
{
  X<int> xi;
  cout << "xi.s= " << xi.s <<endl;/// xi.s = 10
 
  X<char*> xc;
  cout << "xc.s= " << xc.s <<endl;/// xc.s = Hello
  return 0;
}


No comments:

Post a Comment