如何在Meyers Singleton模式中访问衍生的构造函数

How to access derived constructor in Meyers singleton pattern

本文关键字:访问 构造函数 模式 Meyers Singleton      更新时间:2023-10-16

我的代码:

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();
  };