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 允许基类访问派生类的成员,从而实现代码的复用和扩展。基类可以在不知道具体派生类的情况下,调用派生类的特定功能。
相关推荐
hetao17338372 小时前
2026-10-22~23 hetao1733837 的刷题记录
c++·算法
王老师青少年编程3 小时前
2025年6月GESP真题及题解(C++三级): 选择题和判断题(题解)
c++·真题·gesp·答案·csp·三级·信奥赛
卡卡~~4 小时前
“101计划”核心课程实践教材《数据实验结构指导-C++语言版》题目集
开发语言·c++·学习·算法
lengxuenong5 小时前
树状数组 · 信息学学习手册1-求和3个模板
c++·学习·算法·青少年编程
ShineWinsu6 小时前
对于Qt:信号与槽的解析
c++·qt·gui·lambda·信号·信号与槽·槽函数
WL学习笔记6 小时前
使用string类
c++·后端·string类
xxxiugou1236 小时前
链表算法题精讲:从两数相加到K组翻转
数据结构·c++·算法·链表
HAPPY酷6 小时前
C++ 自定义内存池优化点云处理:从裸指针到 RAII 自动回收
开发语言·c++
是2的10次方啊7 小时前
设计模式与生活①:你的脸,为什么不能有第二个?
设计模式
zhangdaliangmvp8 小时前
快速排序的学习理解:从基础分治到三路划分优化
c++·学习·算法