C++学习:CRTP 模式是什么

CRTP(Curiously Recurring Template Pattern,奇异递归模板模式)是 C++ 中的一种设计模式。

基本概念

CRTP 是指一个类(通常是基类)以其派生类作为模板参数的模式。其基本形式如下:

cpp 复制代码
template <typename Derived>
class Base {
// 基类的成员函数可以使用 Derived 类型
};

class Derived : public Base<Derived> {
// 派生类的定义
};

主要用途和优势

  • 静态多态性
    CRTP 可以实现静态多态,即在编译时确定调用的函数,避免动态多态(通过虚函数实现)带来的运行时开销
cpp 复制代码
template <typename Derived>
class Shape {
public:
void draw() {
static_cast<Derived*>(this)->drawImpl();
}
};
class Circle : public Shape<Circle> {
public:
void drawImpl() {
std::cout << "Drawing a circle" << std::endl;
}
};

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

int main() {
Circle circle;
Square square;
circle.draw(); // 调用 Circle 的 drawImpl
square.draw(); // 调用 Square 的 drawImpl
return 0;
}

在这个例子中,Shape 类的 draw 函数通过 static_cast 将 this 指针转换为 Derived 类型,然后调用 drawImpl 函数。由于 drawImpl 函数是在编译时确定的,因此没有虚函数调用的开销。

  • 避免虚函数开销
    在某些情况下,虚函数的调用会带来一定的开销,特别是在性能敏感的代码中。CRTP 可以作为一种替代方案,避免虚函数的使用。
  • 代码复用和扩展
    CRTP 允许基类访问派生类的成员,从而实现代码的复用和扩展。基类可以在不知道具体派生类的情况下,调用派生类的特定功能。
相关推荐
lclin_20206 小时前
VS2010兼容|C++系统全能监控工具(彩色界面+日志带单位+完整版)
c++·windows·系统监控·vs2010·编程实战
paeamecium9 小时前
【PAT甲级真题】- Cars on Campus (30)
数据结构·c++·算法·pat考试·pat
UrSpecial9 小时前
从零实现C++轻量线程池
c++·线程池
chh56310 小时前
C++--模版初阶
c语言·开发语言·c++·学习·算法
会编程的土豆11 小时前
01背包与完全背包详解
开发语言·数据结构·c++·算法
hetao173383712 小时前
2026-04-12~14 hetao1733837 的刷题记录
c++·算法
智者知已应修善业12 小时前
【51单片机4位数循环小数位移数值位移】2023-6-9
c++·经验分享·笔记·算法·51单片机
王璐WL13 小时前
【C++】string,vector和list对比
c++·list
不爱吃炸鸡柳13 小时前
算法复杂度从入门到精通:时间与空间复杂度全解析
开发语言·c++·算法
拳里剑气13 小时前
C++算法:二分查找
c++·算法·二分查找·学习方法