gpt4 book ai didi

c++ - 派生类的单例模式

转载 作者:太空狗 更新时间:2023-10-29 20:53:54 31 4
gpt4 key购买 nike

在普通的单例模式中,单例类实际上是“密封”的(无法派生):

class A
{
private:
static A m_instance; // instance of this class, not a subclass

// private ctor/dtor, so class can't be derived
A();
~A();

public:
static A& GetInstance() { return m_instance; }

...
};

您将如何编写一个本应派生的类,但其派生类只能实例化一次?

最佳答案

How would you write a class that is meant to be derived, but whose derived class should only be instantiated once?

您可以使用 CRTP意识到这一点:

template<typename Derived>
class A
{
protected: // Allow to call the constructor and destructor from a derived class
A();
~A();

public:
static T& GetInstance() {
static T theInstance; // Better way than using a static member variable
return theInstance;
}

...
};

然后像这样使用

class B : public A<B> {
// Specific stuff for derived class
};

请注意,如果基类提供了一些基于派生类提供的接口(interface)的通用实现(除了 GetInstance() 函数),这种方式最有意义。

每当需要调用基类中的派生类时,您都可以安全地使用 static_cast<Derived*>(this)访问它(不需要 virtual 或纯 virtual 函数):

 template<typename Derived> 
void A<Derived>::doSomething {
// Execute the functions from Derived that actually implement the
// warranted behavior.
static_cast<Derived*>(this)->foo();
static_cast<Derived*>(this)->bar();
}

关于c++ - 派生类的单例模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40980034/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com