Static Class member in Class Template
-> Each instantiation of class template has its own copy of member static variables. For example, in the following program there are two instances collection and collection. So two copies of static variable count exist.
// C++ program to demonstrate Static Class member in Class Template.
#include <iostream>
template <class T> class Collection
{
public:
static int count; //static declaration
Collection()
{
count++;
}
};
// We initialise the static like this:
template<class T>
int Collection<T>::count = 0;
int main()
{
Collection<int> v;
Collection<int> w;
Collection<char> x;
Collection<float> y;
Collection<int> z;
std::cout << Collection<int>::count << std::endl;
std::cout << Collection<char>::count << std::endl;
std::cout << Collection<float>::count << std::endl;
return 0;
}
OUTPUT:
3
1
1
-> Each instantiation of class template has its own copy of member static variables. For example, in the following program there are two instances collection and collection. So two copies of static variable count exist.
// C++ program to demonstrate Static Class member in Class Template.
#include <iostream>
template <class T> class Collection
{
public:
static int count; //static declaration
Collection()
{
count++;
}
};
// We initialise the static like this:
template<class T>
int Collection<T>::count = 0;
int main()
{
Collection<int> v;
Collection<int> w;
Collection<char> x;
Collection<float> y;
Collection<int> z;
std::cout << Collection<int>::count << std::endl;
std::cout << Collection<char>::count << std::endl;
std::cout << Collection<float>::count << std::endl;
return 0;
}
OUTPUT:
3
1
1