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 允许基类访问派生类的成员,从而实现代码的复用和扩展。基类可以在不知道具体派生类的情况下,调用派生类的特定功能。
相关推荐
Doris_20232 小时前
代码格式化 使用oxfmt
设计模式·架构·前端框架
Doris_20233 小时前
说一说ESLint+Prettier生效的原理
前端·设计模式·架构
Pomelooooo4 小时前
把 git commit 这件事,彻底交给 AI ——一个工程化 /git-commit 命令的设计与落地
设计模式
玖釉-4 小时前
二叉树展开为链表:从先序遍历到原地指针重排
c++·windows·算法·leetcode·链表
Mister西泽4 小时前
C++ Primer Plus 第六版 编程练习题及详细答案
开发语言·c++·学习·visual studio
Qt程序员4 小时前
从上电到系统就绪:ARM+U-Boot 嵌入式 Linux 启动流程
linux·运维·c++·内核·设备树·嵌入式·ram
invicinble5 小时前
设计模式(类的拓扑结构)(描述总纲)
设计模式·原型模式
cany10005 小时前
C++ -- lambda捕获
c++
Kilicc_6 小时前
C++知识点—03 <C++宏代码生成/宏反射写法>
c++
invicinble8 小时前
设计模式(类的拓扑结构)(为什么会产生设计模式,以及什么是设计模式)
linux·服务器·设计模式