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

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{
     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.


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

class MyBaseClass {
    static int numberAlive;

template <typename T>
class TemplateClass : public MyBaseClass {
    TemplateClass(){ numberAlive++; }
   ~TemplateClass(){ numberAlive--; }

Need Your Help

How to change a widget's font style without knowing the widget's font family/size?

python user-interface fonts tkinter

Is there a way to change a Tkinter widget's font style without knowing the widget's font family and font size?

How to update data with a VBO and Pyglet

python opengl vbo pyglet

I would like to make a mesh with Pyglet that is changing every frame. Therefore I need to update the vertices very often and I thought that a VBO would be the fastest way to go here (correct me if ...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.