在我的項目之一,我用同樣的方法CRTP(從enable_crtp
派生)在回答1瀏覽:How do I pass template parameters to a CRTP?如何處理CRTP的類層次?
不過,我有必要從派生類派生了。有沒有什麼辦法讓與了落回到剛纔的static_cast this指針,但是通過使用來自啓用CRTP基類的自()方法,這項工作?
#include "EnableCRTP.h"
template<typename DERIVED>
class BASE : public EnableCRTP<DERIVED>
{
friend DERIVED;
public:
void startChain()
{
self()->chain();
}
};
template<typename DERIVED>
class Derived1 : public BASE<Derived1<DERIVED> >
{
public:
void chain()
{
std::cout << "Derived1" << std::endl;
//self()->chain2(); <- compile Error
static_cast<DERIVED*>(this)->chain2(); // <-Works
}
};
class Derived2 : public Derived1<Derived2>
{
public:
void chain2()
{
std::cout << "Derived2" << std::endl;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
Derived2 der;
der.startChain();
return 0;
}