【小笔记】奇异递归模版模式CRTP:优雅的静态分派

CRTP 可以以模版继承的方式实现静态分派。

与纯靠模版实现静态分派的方式相比:更加优雅,方便编码与实现,更好理解;或者说,CRTP 本身就是用模版实现分派的一种良好实践。

与多态相比:

  • 编程模式近似。
  • 缺点:不能实现动态分派,原因:无法定义一个 Base * b;,因为没有指定模版参数。代码大小可能会因为模版生成而膨胀。
  • 优点:省略虚表跳转的开销。

例子:

#include<iostream>

template <typename T>
class Base {
public:
    int num{};
    void base_print() { reinterpret_cast<T* const>(this)->print(); }

protected:
    Base() = default;
};

class D1 : public Base<D1> {
public:
    explicit D1(int i = 0) { num = i; }
    void print() { std::cout << "I'm D1, num=" << num << std::endl; }
};

class D2 : public Base<D2> {
public:
    explicit D2(int i = 0) { num = i; }
    void print() { std::cout << "I'm D2, num=" << num << std::endl; }
};

template <typename T>
void dispatch(Base<T> * b) {
    b -> base_print();
}

int main()
{
    // Base * b;

    D1* d1 = new D1(1);
    D2* d2 = new D2(2);

    d1->base_print();
    d2->base_print();

    dispatch(d1);
    dispatch(d2);

    delete d1;
    delete d2;

    return 0;
}

有参考:https://blog.csdn.net/popvip44/article/details/72910201

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值