Is it possible to make a generic singleton? I want to create something I can just inherit from and get the functionality of a singleton. I’m having trouble with using templates with static members.
Shouldn’t this work?
**
UPDATED
**
Thanks for the replies so far. So now my problem is that GameEngine can’t see it’s own constructor. I know it’s private but still.
Singleton.h
template <typename T>
class Singleton
{
private:
static std::shared_ptr<T> m_Instance;
public:
static std::shared_ptr<T> Instance();
};
template<typename T>
std::shared_ptr<T> Singleton<T>::m_Instance = nullptr;
template<typename T>
std::shared_ptr<T> Singleton<T>::Instance()
{
if(m_Instance == nullptr)
m_Instance = std::make_shared<T>();
return m_Instance;
}
GameEngine.h
class GameEngine : public Singleton<GameEngine>
{
private:
GameEngine();
};
The best way to create a singleton is as follows:
The e variable will be (thread-safely) initialized on first call to instance, and it will be destroyed on orderly process exit. The private/deleted constructors prevent a second instance from ever being created.