C++ Template Class with Static Members - Same for all types of the class

Go To StackoverFlow.com

13

If you have a template class with a static variable, is there any way to get the variable to be the same across all types of the class, rather than for each one?

At the moment my code is like this:

 template <typename T> class templateClass{
 public:
     static int numberAlive;
     templateClass(){ this->numberAlive++; }
     ~templateClass(){ this->numberAlive--; }
};

template <typename T> int templateClass<T>::numberAlive = 0;

And main:

templateClass<int> t1;
templateClass<int> t2;
templateClass<bool> t3;

cout << "T1: " << t1.numberAlive << endl;
cout << "T2: " << t2.numberAlive << endl;
cout << "T3: " << t3.numberAlive << endl;

This outputs:

 T1: 2
 T2: 2
 T3: 1

Where as the desired behaviour is:

 T1: 3
 T2: 3
 T3: 3

I guess I could do it with some sort of global int that any type of this class increments and decrements, but that doesnt seem very logical, or Object-Oriented

Thank you anyone who can help me implement this.

2012-04-05 22:16
by jtedit
Will these classes be instantiated on multiple threads? Post increment/decrement is not thread safe - ta.speot.is 2012-04-05 22:18
@ta.speot.is: No operations are natively thread-safe. I'm not sure why that's relevant here; no one mentioned threads - Oliver Charlesworth 2012-04-05 22:21
Oh, yeah, these will probably need to be used on multiple threads, I will have to look into that - jtedit 2012-04-05 22:22
And suddenly...the plot thickens - chris 2012-04-05 22:23
@OliCharlesworth Because of the comment below yours - ta.speot.is 2012-04-05 22:24
@ta.speot.is: Ah, non-causality - Oliver Charlesworth 2012-04-05 22:24


29

Have all the classes derive from a common base class, whose only responsibility is to contain the static member.

class MyBaseClass {
protected:
    static int numberAlive;
};

template <typename T>
class TemplateClass : public MyBaseClass {
public:
    TemplateClass(){ numberAlive++; }
   ~TemplateClass(){ numberAlive--; }
};
2012-04-05 22:18
by Oliver Charlesworth
Ads