作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我的代码:
template<class T>
class Singleton {
public:
static T& instance() {
static T obj;
return obj;
}
protected:
Singleton() { }
Singleton(Singleton const& other);
void operator=(Singleton const& other);
};
class Derived : public Singleton<Derived> {
protected:
Derived() { }
};
void test() {
Derived::instance();
}
我在 static T obj
行收到此错误:
‘Derived::Derived()’ is protected
Derived() { }
^
我该如何解决这个问题?也许使用 friend
关键字?但这会有点尴尬。
注意: 我知道 Meyers 单例的名称和想法,但我自己实现它的原因是我找不到我第一次阅读它的地方。我以为它在“Effective C++”或“More Effective C++”中,但我在那里找不到。而且我在网上找到的例子没有使用CRTP-generalization。
最佳答案
使 Singleton
instance
函数成员成为 Derived
的友元:
struct Derived{
//...
friend Derived& Singleton<Derived>::instance();
};
关于c++ - 如何访问 Meyers 单例模式中的派生构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46040154/
我最近购买了《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
我是一名优秀的程序员,十分优秀!