Singleton and Abstract base class in C++

c++, singleton

Solution

You'd want to use something like

IFoo my_foo = Singleton<Foo>::Instance();
my_foo->foo();

Basically you'll have to instantiate the template Singleton using a concrete class (in this case, your class Foo) and given that your Foo derives from IFoo you can refer to it through a base pointer. You cannot directly instantiate a template using an incomplete or abstract class.

Problem

Recently I got question on implement Singleton but abstract base class involved. Suppose we have class hierarchy like this: ``` class IFoo {...}; // it's ABC class Foo : public IFoo {...}; ``` we have singleton class defined as follows: ``` template <typename T> class Singleton { public: static T* Instance() { if (m_instance == NULL) { m_instance = new T(); } return m_instance; } private: static T* m_instance; }; ``` So if I want to use like following: `IFoo::Instance()->foo();` what should I do? If I do this: `class IFoo : public Singleton<IFoo> {...};` it won't work since Singleton will call IFoo's ctor but IFoo is a ABC so can not be created. And this: `class Foo : public IFoo, public Singleton<Foo> {...};` can't work too, because this way class IFoo doesn't have the interface for method Instance(), so the call `IFoo::Instance()` will fail. Any ideas?

Original source

Related problems