我将将具有纯虚拟方法纯继承性的代码转换为CRTP,以避免虚拟方法(see here)的开销。

直到我在CRTP实现中删除了对调用方法的注释(转换为compilation error: use of undeclared identifier 'T'),转换都可以正常工作,如何在CRTP中实现相同的调用方法,而在普通继承中没有问题?换句话说,是否可以像普通继承那样将指针传递给基类?

当然,我可以通过将调用方法移到类模板中来解决问题,但是就我的用例而言,它不属于那里(我在这里没有给出我的实际代码,这很长)。有任何想法吗?

转换前的代码如下:

#include <iostream>

class Base
{
public:
    void interface() {
        implementation();
    }
    virtual void implementation() = 0;
};

class Derived1 : public Base
{
public:
    void implementation() {
        std::cout << "Hello world 1" << std::endl;
    }
};

class Derived2 : public Base
{
public:
    void implementation() {
        std::cout << "Hello world 2" << std::endl;
    }
};

void call(Base *b) {
    b->interface();
    // ... do other things ...
}

int main() {
   Derived1 d1;
   Derived2 d2;
   call(&d1);
   call(&d2);
}

转换后的代码(CRTP)如下:
#include <iostream>

template <class T>
class Base
{
public:
    void interface() {
        static_cast<T*>(this)->implementation();
    }
};

class Derived1 : public Base<Derived1>
{
public:
    void implementation() {
        std::cout << "Hello world 1" << std::endl;
    }
};

class Derived2 : public Base<Derived2>
{
public:
    void implementation() {
        std::cout << "Hello world 2" << std::endl;
    }
};

//void call(Base<T> *b) {
//    b->interface();
//    // ... do other things ...
//}

int main() {
   Derived1 d1;
   Derived2 d2;
   //call(&d1);
   //call(&d2);
   d1.interface();
   d2.interface();
}

最佳答案

您错过了一些语法。正确声明:

template<class T> // <--- this was missing
void call(Base<T> *b) {
    b->interface();
}

关于c++ - 如何在CRTP实现中传递基类指针,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51535255/

10-11 16:28