如何在 CRTP 实现中传递 base class 指针

How can I pass base class pointer in a CRTP implementation

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

在我删除 CRTP 实现中对调用方法的注释之前,转换工作得很好(它给出 compilation error: use of undeclared identifier 'T')我如何在 CRTP 中实现相同的调用方法,这在普通继承中没有问题?换句话说,是否可以像在普通继承中那样传递指向基 class 的指针?

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

转换前的代码如下:

#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();
}