快速问题。有没有办法继承单例,以使子类成为单例?我已经搜索过了,但我找到的每个单例都是按类实现的,而不是以通用的方式实现的。
快速问题。有没有办法继承单例,以使子类成为单例?我已经搜索过了,但我找到的每个单例都是按类实现的,而不是以通用的方式实现的。
是的,有一种通用的方法。您可以通过CRTP实现单例,例如:
template<typename T>
class Singleton
{
protected:
Singleton() noexcept = default;
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
virtual ~Singleton() = default; // to silence base class Singleton<T> has a
// non-virtual destructor [-Weffc++]
public:
static T& get_instance() noexcept(std::is_nothrow_constructible<T>::value)
{
// Guaranteed to be destroyed.
// Instantiated on first use.
// Thread safe in C++11
static T instance{};
return instance;
}
};
class MySingleton: public Singleton<MySingleton>
{
// needs to be friend in order to
// access the private constructor/destructor
friend class Singleton<MySingleton>;
public:
// Declare all public members here
private:
MySingleton()
{
// Implement the constructor here
}
~MySingleton()
{
// Implement the destructor here
}
};
getInstance()
方法,第一次调用时创建类的唯一实例,因此在实例化单例类的类型上是静态绑定的。我不认为拥有一个单例层次结构会立即有用。但如果你坚持要有一个,你可以考虑将getInstance
方法设为virtual
并在扩展父单例的类中重写它。class Singleton {
public virtual Singleton * getInstance() const
{
// instantiate Singleton if necessary
// return pointer to instance
}
...
};
class MySingleton : public Singleton {
// overrides Singelton's getInstance
public virtual MySingleton * getInstance() const
{
// instantiate MySingleton if necessary
// return pointer to instance
}
};