C++:奇异递归模板模式(CRTP模式)

奇异递归模板模式

理论说明

奇异递归模板模式(Curiously Recurring Template Pattern, CRTP) 是一种设计模式,其原理很简单:

继承者将自身作为模板参数传递给基类

如下:

struct Foo : SomeBase<Foo>
{
...
}

CRTP模式的功能

静态多态

通过 CRTP,可以在编译时实现多态行为,而不是依赖于运行时多态(如虚函数表)。这可以减少运行时开销,因为编译器可以内联函数调用。

#include<iostream>
using namespace std;

template <typename Derived>
class Shape {
public:
        void draw() {
                static_cast<Derived*>(this)->draw();
        }
};

class circle : public Shape<circle> {
public:
        void draw() {
                cout << "Drawing a circle" << endl;
        }
};

class square : public Shape<square> {
public:
        void draw() {
                cout << "Drawing a square" << endl;
        }
};

int main() {
        circle circle;
        square square;
        circle.draw();
        square.draw();
        return 0;
}

运行结果:

Drawing a circle
Drawing a square

强制静态接口

CRTP 可以用于确保派生类实现某些接口,因为基类可以调用派生类的方法。如果派生类未实现这些方法,将在编译时产生错误。

template <typename Derived>
class Interface {
public:
    void perform() {
        static_cast<Derived*>(this)->perform();
    }
};

class Implementation : public Interface<Implementation> {
public:
    void perform() {
        std::cout << "Performing implementation" << std::endl;
    }
};

在上面的代码中,基类保证了子类必须有 perform 函数的重写,也就是强制接口。

编译时多态优化

CRTP 可以帮助实现一些模板元编程技术,优化代码在编译时的行为。例如,EBO(Empty Base Optimization)可以利用 CRTP 来减少对象的内存占用。

template <typename T>
class EmptyBase {
};

class Derived : public EmptyBase<Derived> {
};

在 C++ 中,如果一个类是空的(即没有非静态成员变量,没有虚函数,没有虚基类),它通常不会占用任何内存空间。这个优化称为 空基类优化(Empty Base Optimization, EBO)。当一个派生类继承一个空基类时,编译器可以将这个基类的存储空间与派生类的其他成员共享,从而减少内存占用。

用下面的代码来做解释:

#include <iostream>

template <typename T>
class EmptyBase {
    // Empty base class
};

class NonEmptyDerived : public EmptyBase<NonEmptyDerived> {
public:
    int data;
};

int main() {
    std::cout << "Size of EmptyBase: " << sizeof(EmptyBase<NonEmptyDerived>) << std::endl;
    std::cout << "Size of NonEmptyDerived: " << sizeof(NonEmptyDerived) << std::endl;
    return 0;
}


输出结果:
1

解释
  • EmptyBase<NonEmptyDerived> 是一个空基类,按照一般规则,空类通常会占用 1 字节的空间来保证不同对象具有唯一的地址。

  • NonEmptyDerived 继承自 EmptyBase<NonEmptyDerived>,并且有一个 int 成员 data。通常 int 占用 4 字节空间。

由于 EmptyBase 是空的,编译器会应用 EBO,将 EmptyBase 的存储空间与 NonEmptyDerived 的 data 成员共享。因此,最终的 NonEmptyDerived 对象大小仅为 4 字节,即 int 的大小,而没有额外增加由于基类而带来的存储开销。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

若亦_Royi

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值