c++ 为什么CRTP在以下功能中不工作?

x6yk4ghg  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(125)

我在学习CRTP C++模式
我的代码

template<class Type>
class BaseOrder {
public:
    void sendOrder() {static_cast<Type*>(this)->send();}
    void send() { cout << "Send Base" << endl;}
};

class DerivedOrder1 : public BaseOrder<DerivedOrder1> {
public:
    void send() { cout << "Send DerivedOrder1" << endl;}
};

class DerivedOrder2 : public BaseOrder<DerivedOrder2> {
public:
    void send() { cout << "Send DerivedOrder2" << endl;}
};

template<class T>
void handleOrder(BaseOrder<T> order) {
    order.send();
}

int main() {
    BaseOrder<DerivedOrder1> obj1;
    handleOrder(obj1); // Send Base

    BaseOrder<DerivedOrder2> obj2;
    handleOrder(obj2); // Send Base
}

字符串
我看到输出:

Send Base
Send Base


但我预计

Send DerivedOrder1
Send DerivedOrder2


如何修复我的代码?我错过了什么吗?

jm81lzqq

jm81lzqq1#

你的代码中有几个错误:
send不是virtual,你可能想调用sendOrder。你应该通过引用传递这个参数,以避免切片,这将使调用sendOrder UB,因为转换将是无效的:

template <class T>
void handleOrder(BaseOrder<T>& order) {
    order.sendOrder();
}

字符串
在main中,你不创建派生类,它应该是

DerivedOrder1 obj1;
handleOrder(obj1); // Send Base

DerivedOrder2 obj2;
handleOrder(obj2); // Send Base


Demo
为了避免这些错误,一个改进是将一些方法protected

template<class Type>
class BaseOrder {
protected:
    BaseOrder() = default;
    BaseOrder(const BaseOrder&) = default;
    BaseOrder& operator=(const BaseOrder&) = default;
public:
// ..
};


Demo

相关问题