首页 > 解决方案 > 如何在 CRTP 实现中传递基类指针

问题描述

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

转换工作得非常好,直到我删除了 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();
}

标签: c++crtp

解决方案


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

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

推荐阅读