I am trying to implement a template class with a static member. Classes that are derived from the template class shall be instantiated without the need to write extra code.
Here is my naive (and not successful) approach:
Singleton.h:
template <class T> class Singleton {
protected:
Singleton();
static T instance_;
}
// explicit instantiation of 'instance_' ???,
// where 'instance_' is an instance of the derived class
template <class T> T Singleton<T>::instance_;
ConcreteA.h:
class ConcreteA : public Singleton<ConcreteA> {
public:
ConcreteA();
void foo();
}
main.c:
int main() {
// an instance of ConcreteA should have been created (no extra code)!!!
return 0;
}
Is there a way to force the instantiation of ConcreteA by just deriving ConcreteA from Singleton, without writing extra instantiation code?
A dirty workaround is to call an method on instance_ in the ConcreteA constructor, for example:
ConcreteA.c
ConcrereA::ConcreteA { instance_.foo(); }
Are there better workarounds?