In c# static members are unique for each generic class like in this example
using System;
//A generic class
public class GenTest<T>
{
//A static variable - will be created for each type on refraction
static CountedInstances OnePerType = new CountedInstances();
//a data member
private T mT;
//simple constructor
public GenTest(T pT)
{
mT = pT;
}
}
//a class
public class CountedInstances
{
//Static variable - this will be incremented once per instance
public static int Counter;
//simple constructor
public CountedInstances()
{
//increase counter by one during object instantiation
CountedInstances.Counter++;
Console.WriteLine(Counter);
}
}
public class staticTest {
static void Main(string[] args) {
//main code entry point
//at the end of execution, CountedInstances{{Not a typo|.}}Counter = 2
GenTest<int> g1 = new GenTest<int>(1);
GenTest<int> g11 = new GenTest<int>(11);
GenTest<int> g111 = new GenTest<int>(111);
GenTest<double> g2 = new GenTest<double>(1.0);
}
}
from http://en.wikipedia.org/wiki/Generic_programming
What about c++? I have tried out to check that myself but translation to c++ seems to ignore the static member.
#include <iostream>
using namespace std;
class CountedInstances {
public:
static int Counter;
CountedInstances() {
Counter++;
cout << Counter << endl;
}
};
int CountedInstances::Counter = 0;
template<class T> class GenTest {
static CountedInstances OnePerType;
T mT;
public:
GenTest(T pT) {
mT = pT;
}
};
template<class T> CountedInstances GenTest<T>::OnePerType = CountedInstances();
int main() {
GenTest<int> g1(1);
GenTest<int> g11(11);
GenTest<int> g111(111);
GenTest<double> g2(1.0);
cout << CountedInstances::Counter << endl;
//CountedInstances c1;
//CountedInstances c2;
}
In this answer I can see that in c++ static members are unique for each specialization, however, my code seems legit but the static member OnePerType
is ignored.
I thought that for each GenTest<>
Counter will be printed what happens only when I create objects of type CountedInstances
as in the comment. Why is that?