快问.无论如何都要继承单例,以便子类是单例吗?我已经四处寻找,但我能找到的每一个单身都是按照课程实现的,而不是通用的.
是的,有一种通用的方式.您可以通过CRTP实现Singleton ,例如:
templateclass Singleton { protected: Singleton() noexcept = default; Singleton(const Singleton&) = delete; Singleton& operator=(const Singleton&) = delete; virtual ~Singleton() = default; // to silence base class Singleton has a // non-virtual destructor [-Weffc++] public: static T& get_instance() noexcept(std::is_nothrow_constructible ::value) { // Guaranteed to be destroyed. // Instantiated on first use. // Thread safe in C++11 static T instance; return instance; } };
然后从中得出让你的孩子成为单身人士:
class MySingleton: public Singleton{ // needs to be friend in order to // access the private constructor/destructor friend class Singleton ; public: // Declare all public members here private: MySingleton() { // Implement the constructor here } ~MySingleton() { // Implement the destructor here } };
Live on Coliru