作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
在普通的单例模式中,单例类实际上是“密封”的(无法派生):
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/
我最近购买了《C 编程语言》并尝试了 Ex 1-8这是代码 #include #include #include /* * */ int main() { int nl,nt,nb;
早上好!我有一个变量“var”,可能为 0。我检查该变量是否为空,如果不是,我将该变量保存在 php session 中,然后调用另一个页面。在这个新页面中,我检查我创建的 session 是否为空,
我正在努力完成 Learn Python the Hard Way ex.25,但我无法理解某些事情。这是脚本: def break_words(stuff): """this functio
我是一名优秀的程序员,十分优秀!