I’ve got a template Singleton class that I use for a certain amount of important components of my code. Using a Singleton code-model is not the point of this question.
Now, I’d like to add to this class a static counter that is shared by every class that use this template. Let me code that for you (the code is not exhaustive):
template <class T>
class Singleton
{
public:
Singleton(const std::string &name){
printf("%s CTOR call #%d\n", name.c_str(), _counter);
_counter++;
}
virtual ~Singleton(){}
private:
static int _counter; // I want this to be shared by all classes
}
// I can only initialize it like this; sadly
template<class T>
int Singleton<T>::_counter = 0;
// main code (simplified):
Singleton<MyClass1>("MyClass1") c1;
Singleton<MyClass2>("MyClass2") c2;
Singleton<MyClass3>("MyClass3") c3;
Singleton<MyClass4>("MyClass4") c4;
Expected output:
MyClass1 CTOR call #0
MyClass2 CTOR call #1 // counter is incremented
MyClass3 CTOR call #2
MyClass4 CTOR call #3
What I get is:
MyClass1 CTOR call #0
MyClass2 CTOR call #0 // counter is not incremented
MyClass3 CTOR call #0
MyClass4 CTOR call #0
Which means the static int is not shared, but rather specific to each class.
How can I have a “not-templated” counter in my template class? Is this possible with a header-only template?
As follows:
Make this a member of your singleton and instead of the member variable, use this…
EDIT: I just re-read your question, you need to make this a member of another type, e.g: