派生するクラスを作成しますが、その派生クラスは一度だけインスタンス化する必要がありますか?
あなたはそれを実現するために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();
}
関連します。http:// stackoverflowの。 com/questions/5739678/c-templates-and-the-singleton-pattern –