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 允许基类访问派生类的成员,从而实现代码的复用和扩展。基类可以在不知道具体派生类的情况下,调用派生类的特定功能。
相关推荐
TonyLee0171 天前
LLVM安装(ubuntu22)
c++
weixin_445054721 天前
力扣热题51
c++·python·算法·leetcode
汉克老师1 天前
GESP2025年12月认证C++七级真题与解析(单选题8-15)
c++·dfs·bfs·二分·强联通分量·gesp7级·gesp七级
JavaBoy_XJ1 天前
行为型-模板模式
设计模式·模板方法模式·模板模式
fqbqrr1 天前
2601C++,pmr管理内存
c++
君义_noip1 天前
【模板:矩阵加速递推】信息学奥赛一本通 1642:【例 2】Fibonacci 第 n 项
c++·线性代数·矩阵·信息学奥赛·csp-s
宠..1 天前
优化文件结构
java·服务器·开发语言·前端·c++·qt
编程之路,妙趣横生1 天前
C++11(上)
c++
微露清风1 天前
系统性学习C++-第十六讲-AVL树实现
java·c++·学习
cpp_25011 天前
P1583 魔法照片
数据结构·c++·算法·题解·洛谷