CRTP是C++中利用模板实现静态多态的惯用法,核心为派生类继承以自身为模板参数的基类,从而在编译期绑定函数调用、避免虚函数开销,并支持接口契约、功能注入与混入复用,但不支持动态多态且错误信息较复杂。

CRTP(Curiously Recurring Template Pattern),中文常译作“奇特递归模板模式”,是 C++ 中一种借助模板实现静态多态的经典技巧。它不是语言标准定义的设计模式,而是一种惯用法(idiom),核心思想是:派生类继承自一个以自身为模板参数的基类。
典型结构如下:
<font size="2">template <typename Derived>
struct Base {
void interface() {
static_cast<Derived*>(this)->implementation(); // 静态调用派生类函数
}
};
<p>struct MyDerived : Base<MyDerived> {
void implementation() { /<em> 具体逻辑 </em>/ }
};</font>关键点:
Derived 就是子类自身(如 MyDerived)Base<myderived></myderived> 显式继承,构成“递归”外观(类名出现在自己的继承列表中)static_cast<derived>(this)</derived> 安全转换,直接调用子类的函数 —— 编译期绑定,无虚函数开销CRTP 主要用于需要“编译期多态”或“零成本抽象”的场合:
立即学习“C++免费学习笔记(深入)”;
size()、data()),否则编译失败EnableSharedFromThis 的简化版、可比较性增强(operator== 自动生成)利用 CRTP 让派生类只需定义 equal_to,就能获得完整的比较操作符:
<font size="2">template <typename Derived>
struct EqualityComparable {
friend bool operator==(const Derived& a, const Derived& b) {
return static_cast<const Derived&>(a).equal_to(b);
}
friend bool operator!=(const Derived& a, const Derived& b) {
return !(a == b);
}
};
<p>struct Point : EqualityComparable<Point> {
int x, y;
bool equal_to(const Point& other) const { return x == other.x && y == other.y; }
};</font>这样 Point{1,2} == Point{1,2} 就能直接工作,且没有运行时开销。
CRTP 强大但需谨慎使用:
基本上就这些。CRTP 是模板元编程里“以空间换时间、以编译换运行”的典型体现 —— 写起来稍绕,但生成的代码干净高效。用对地方,非常优雅。
以上就是c++++中的CRTP是什么模式_c++奇特递归模板模式应用【模板元编程】的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号