Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/132.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何在类层次结构中处理CRTP?_C++_Templates_Crtp - Fatal编程技术网

C++ 如何在类层次结构中处理CRTP?

C++ 如何在类层次结构中处理CRTP?,c++,templates,crtp,C++,Templates,Crtp,在我的一个项目中,我使用了与答案1相同的CRTP方法(源自enable\u CRTP): 然而,我也需要从派生类派生。是否有任何方法可以使这项工作不返回到仅静态抛出this指针,而是使用Enable CRTP基类中的self()方法 #include "EnableCRTP.h" template<typename DERIVED> class BASE : public EnableCRTP<DERIVED> { friend DERIVED; public:

在我的一个项目中,我使用了与答案1相同的CRTP方法(源自
enable\u CRTP
):

然而,我也需要从派生类派生。是否有任何方法可以使这项工作不返回到仅静态抛出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;
}
#包括“EnableCRTP.h”
模板
类库:public EnableCRTP
{
朋友衍生;
公众:
void startChain()
{
self()->chain();
}
};
模板
类Derived1:公共基
{
公众:
空链()
{

std::cout您可以将派生最多的类作为CRTP基类的模板参数,这样它就可以访问其所有成员

template<typename DERIVED>
class Derived1 : public BASE<Derived1<DERIVED> >
模板
类Derived1:公共基
使用:

模板
类Derived1:公共基

您的代码还存在其他问题。例如,您不能像您那样直接调用
self()
,因为编译器不知道
self
是基类(依赖于模板参数)的成员。相反,请调用
this->self()
。请参见。

若要执行所需操作,您只需通过CRTP传递最派生的类。在这种情况下,您需要将Derived1的定义更改为以下内容:

template<typename DERIVED>
class Derived1 : public BASE< DERIVED >
{
public:
    void chain()
    {
        std::cout << "Derived1" << std::endl;

        this->self()->chain2(); // should work now
        //static_cast<DERIVED*>(this)->chain2(); // <-Works
    }
};
模板
类Derived1:公共基<派生>
{
公众:
空链()
{
std::cout chain2();//现在应该可以工作了
//静态_cast(this)->chain2()//
template<typename DERIVED>
class Derived1 : public BASE< DERIVED >
{
public:
    void chain()
    {
        std::cout << "Derived1" << std::endl;

        this->self()->chain2(); // should work now
        //static_cast<DERIVED*>(this)->chain2(); // <-Works
    }
};