2016-12-05 16 views
3

ためのSingletonパターン、シングルトンクラスが効果的である(導出することはできません):通常シングルトンパターンでは誘導クラス

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

    ... 
}; 

あなたが導出されることを意図されたクラスを書くが、そのだろうか派生クラスは一度だけインスタンス化する必要がありますか?

+0

関連します。http:// stackoverflowの。 com/questions/5739678/c-templates-and-the-singleton-pattern –

答えて

4

派生するクラスを作成しますが、その派生クラスは一度だけインスタンス化する必要がありますか?

あなたはそれを実現するために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 
}; 

のようなものを使用します(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(); 
} 
+0

'静的なTインスタンス 'は客観的に「より良い」ものですか?確かにどちらも同じものにコンパイル? – Michael

+1

@Michaelそれは同じものにコンパイルされません。それがより良い理由です。 –

+2

@Michael _Scott MeyerのSingleton_を検索し、それが高度で優れた方法(スレッドの安全性など)である理由を調べます。 –

関連する問題