So I have a simple singleton template base class (minified for question purposes):
template <typename T>
class Singleton {
public:
static T& instance() {
static T me;
return me;
}
};
Now I want to have a “Base class that’s a singleton”:
class Base : public Singleton<Base> {
public:
void print() { std::cout << &instance() << std::endl; }
}
What I want now is deriving children classes from this base class, which are their own singletons:
class A : public Base {
// ...
}
class B : public Base {
// ...
}
Of course if I do this
A::instance().print();
B::instance().print();
I get the same address in both cases. Is there a way to accomplish this?
In case you’re wondering what for: I want to program a ResourceManager base class which is being inherited by a class ImageManager, a class ‘AudioManager’, etc. And I’d like them not to share actually the same instance, but still having only one instance per manager…
You will have to make Base a template and pass that to
Singleton, then inherit fromBase<A>if you wish to achieve this. Or, if you want Base to be a Singleton and A/B to be a Singleton, then they will have to inherit fromSingleton<A>,Singleton<B>in addition toBase.But dear lord, man, Singletons are a curse on you and your children for a hundred generations. Why would you do that to yourself?