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 允许基类访问派生类的成员,从而实现代码的复用和扩展。基类可以在不知道具体派生类的情况下,调用派生类的特定功能。
相关推荐
Dylan的码园14 分钟前
A+B问题 进制处理【逻辑控制 运算符】
c++·算法
hetao173383741 分钟前
2026-09-27~28 hetao1733837 的刷题记录
c++·算法
2601_9622186143 分钟前
C++的几种编译器的实现
开发语言·c++
多弗朗皮卡丘1 小时前
C++ stack和queue
开发语言·c++·deque·queue·stack·容器适配器
lengxuenong1 小时前
枚举及其优化学习手册
c++·学习·算法·青少年编程
Benny_Tang1 小时前
P9527 [JOIST 2022] 洒水器 / Sprinkler 题解
c++·算法
垆边人似月.2 小时前
华为机考题:最小代价爬楼梯
c语言·c++
可涵不会debug2 小时前
C++ std::bind 实战教程:线程池、回调场景全覆盖
linux·开发语言·c++
垆边人似月.3 小时前
华为机考题:二叉树的最大路径和
c语言·c++
2601_962218613 小时前
深入理解C++中的thread_local线程局部变量的应用
开发语言·c++