【发布时间】:2012-11-07 08:44:40
【问题描述】:
在我的一个项目中,我使用与此处的答案 1 相同的 CRTP 方法(源自 enable_crtp):How do I pass template parameters to a 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;
}
【问题讨论】: