如何在Meyers Singleton模式中访问衍生的构造函数
How to access derived constructor in Meyers singleton pattern
我的代码:
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 Singleton的名称和想法的原因,但是我自己实现了它,是因为我找不到我第一次阅读的地方。我认为它要么是在"有效的C "中,要么在"更有效的C "中,但我在那里找不到它。我在网上发现的示例不使用CRTP将军。
使Singleton
instance
函数成员Derived
的朋友:
struct Derived{
//...
friend Derived& Singleton<Derived>::instance();
};
相关文章:
- 固有构造函数的字符和访问级别
- C++:为什么无法在派生类中访问受保护的构造函数?
- 使用 CTRP 时,是否访问访问父构造函数 UB 中的子属性?
- c++ cuda:cudaMalloc在构造函数之外的托管访问
- 使用值初始化访问构造函数?
- 限制variadic模板类中的构造函数访问
- 构造函数无法访问继承类私有 int
- 从派生类访问模板基类的构造函数
- 如何在构造函数中访问类变量以分配它们,而无需在C++中使用此指针
- 访问在构造函数期间创建的值 - C++
- 从析构函数访问模板类构造函数的参数,可以吗?
- 仅当构造函数具有参数时,C++ 公共成员才能访问
- 正确的友元定义,以授予 std::map 对私有默认构造函数的访问权限
- 在派生类的构造函数初始化中无法访问受保护的函数
- 访问构造函数中的非类型模板参数
- 我应该使用<Object> shared_ptr myObject = (shared_ptr) <Object>new Object() 来访问私有构造函数吗?
- 无法访问构造函数定义之外的变量
- 多个线程 - 无法访问构造函数设置的类成员变量
- 在C++中访问构造函数
- 无法访问构造函数中类的继承成员