2017-09-04 25 views
3

我的代碼:如何訪問派生構造函數邁爾斯單例模式

‘Derived::Derived()’ is protected 
    Derived() { } 
    ^

我該如何解決這個問題:

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行收到此錯誤?也許使用friend關鍵字?但那會有點尷尬。

注意:我意識到Meyers單身人士的名字和想法的原因,但是我自己實現它,是因爲我無法找到我第一次閱讀它的地方。我認爲這是在「有效的C++」或「更有效的C++」,但我無法在那裏找到它。我在網上找到的例子並沒有使用CRTP泛化。

+0

的Singleton模式已經被遺棄了自己的創造者以後。你應該避免使用它。邁耶斯不是作者之一。 – Ron

+0

這確實不是最好的主意。只需從CppCon2016(https://www.youtube.com/watch?v=23xDn3ReH7E)這5分鐘的視頻,這是有趣和有益的! (命名空間是singleton [extensible]) – Oliv

回答

1

Singletoninstance函數成員的Derived的朋友:

struct Derived{ 
    //... 
    friend Derived& Singleton<Derived>::instance(); 
    }; 
+0

甚至更​​簡單:'public Singleton { friend class Singleton ; ....' –

相關問題