Yes, there is a general way. You can implement Singleton using CRTP , for example:
template<typename T>
class Singleton
{
protected:
Singleton() noexcept = default;
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
virtual ~Singleton() = default;
public:
static T& get_instance() noexcept(std::is_nothrow_constructible<T>::value)
{
static T instance;
return instance;
}
};
then output it to make your child Singleton:
class MySingleton: public Singleton<MySingleton>
{
friend class Singleton<MySingleton>;
public:
private:
MySingleton()
{
}
~MySingleton()
{
}
};
Live on Coliru
source
share