你會如何編寫一個想要派生的類,但是派生類只應該被實例化一次?
可以使用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://計算器。 com/questions/5739678/c-templates-and-the-singleton-pattern –