在我的一个项目中,我使用与enable_crtp
答案 1 中相同的 CRTP 方法(源自 ):如何将模板参数传递给 CRTP?
但是我也需要从派生类派生。有什么方法可以使这项工作不回退到仅 static_cast this 指针而是使用 Enable CRTP 基类中的 self() 方法?
#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;
}