# 奇异递归模板模式

奇异递归模板模式（CRTP）是一种 C++ 技术，其中类 `X` 继承自一个接受模板参数 `Z` 的类模板 `Y`，且 `Y` 被特化使得 `Z` 等于 `X`；用代码表示即 `class X : public Y<X>`<sup>[1](https://en.cppreference.com/cpp/language/crtp)</sup>。因此基类模板在编译期就知道其派生类的确切类型，并可在自身接口中使用该类型，最显著的用途是在不使用虚函数的情况下实现编译期多态<sup>[1](https://en.cppreference.com/cpp/language/crtp)</sup>。

| 关键事实 | 详情 |
|---|---|
| 定义 | 类 `X` 派生自以 `Z = X` 实例化的类模板 `Y<Z>`<sup>[1](https://en.cppreference.com/cpp/language/crtp)</sup> |
| 命名 | 由 James Coplien 于 1995 年命名；CRTP 至少自 1991 年起就已被使用，Coplien 是第一个将其正式描述为模式的人<sup>[2](https://www.fluentcpp.com/2017/05/12/curiously-recurring-template-pattern/)</sup><sup> • </sup><sup>[3](https://www.pearsonhighered.com/assets/samplechapter/0/2/0/1/0201734842.pdf)</sup> |
| 核心机制 | 基类用 `static_cast` 将 `*this` 转换为派生类型并直接调用派生类成员，这是一次编译器可以内联的普通调用<sup>[2](https://www.fluentcpp.com/2017/05/12/curiously-recurring-template-pattern/)</sup><sup> • </sup><sup>[4](https://mreid-consulting.github.io/cpp-lessons/lessons/23a-crtp-and-static-polymorphism.html)</sup> |
| 带来的好处 | 无虚调用开销的静态多态，以及访问派生类型本身、其静态成员和其中定义的类型的能力<sup>[5](https://www.foonathan.net/2021/10/crtp-interface/)</sup> |
| 标准库中的使用 | `std::enable_shared_from_this`（C++11）和 `std::ranges::view_interface`（C++20）建立在该模式之上<sup>[1](https://en.cppreference.com/cpp/language/crtp)</sup> |
| 现代替代方案 | C++23 的推导 `this`（P0847）提供了 CRTP 的一种版本，不要求基类以派生类为模板参数<sup>[6](https://devblogs.microsoft.com/cppblog/cpp23-deducing-this/)</sup> |

## 工作原理

该模式有两个部分：继承自一个模板类，以及使用派生类本身作为该基类的模板参数<sup>[2](https://www.fluentcpp.com/2017/05/12/curiously-recurring-template-pattern/)</sup>。从基类对象的角度看，派生对象就是它自己，只是向下转换了，因此基类可以通过转换自身来访问派生类：

```cpp
template <typename T>
class Base {
public:
    void doSomething() {
        T& derived = static_cast<T&>(*this);
        // 使用 derived ……
    }
};

class Derived : public Base<Derived> { };
```

该转换是 `static_cast` 而非 `dynamic_cast`，因为不需要运行时检查：基类的设计就是只被其模板参数继承，不被其他任何东西继承，因此向下转换是内建于设计中的假设<sup>[2](https://www.fluentcpp.com/2017/05/12/curiously-recurring-template-pattern/)</sup>。由于基类通过模板参数知道确切的派生类型，向下转换是编译期的指针调整，随后的调用是编译器可以内联的普通直接调用<sup>[4](https://mreid-consulting.github.io/cpp-lessons/lessons/23a-crtp-and-static-polymorphism.html)</sup>。

编译期多态的典型形式是基类暴露一个接口方法，转发到派生类提供的实现<sup>[1](https://en.cppreference.com/cpp/language/crtp)</sup>：

```cpp
template <class Derived>
struct Base {
    void name() { static_cast<Derived*>(this)->impl(); }
protected:
    Base() = default; // 禁止创建 Base 对象，否则为未定义行为
};
struct D1 : public Base<D1> { void impl() { /* …… */ } };
struct D2 : public Base<D2> { void impl() { /* …… */ } };
```

## 用途

**静态多态。** 基类暴露接口，派生类实现该接口，分派在编译期解析而非通过虚表<sup>[1](https://en.cppreference.com/cpp/language/crtp)</sup>。

**接口样板代码。** 诸如 `foo_interface<Derived>` 的基类可以通过向下转换调用派生类的小型必需方法来实现样板方法，这样每个继承类型都免费获得这些样板代码。与传统继承和虚函数相比，该技术更强大，因为它还可以使用派生类型的类型和静态函数，并且能从 `operator++(int)` 等函数返回正确的派生类型，而虚函数设计若不发生对象切片就无法做到这一点<sup>[5](https://www.foonathan.net/2021/10/crtp-interface/)</sup>。实际应用包括 Boost.STLInterfaces、C++20 的 `std::ranges::view_interface` 以及 lexy 解析库中的 `forward_iterator_interface`<sup>[5](https://www.foonathan.net/2021/10/crtp-interface/)</sup>。

**运算符注入与 Barton–Nackman 技巧。** CRTP 基类可以为任何实现了 `operator+=` 的派生类提供按值返回的 `operator+`，方法是将其自身转换为派生类型<sup>[7](https://www.club.cc.cmu.edu/~ajo/disseminate/book.pdf)</sup>。相关的 Barton–Nackman 技巧出自 John Barton 和 Lee Nackman 的《科学与工程 C++》（1994 年），它将一个非成员函数（通常是运算符）定义为 CRTP 基类内部的 `friend`。该友元函数只有在模板实例化时才进入外围命名空间，对每个具体派生类只发生一次，因此不会发生单一定义规则冲突，且参数依赖查找（ADL）可以定位该函数<sup>[8](https://www.yuzhang.io/notes/system-design/design-pattern/crtp)</sup>。Barton 和 Nackman 称之为受限模板展开，因为它避免了会适用于所有类型的无约束 `operator==(T, T)` 模板；在标准 C++ 中，注入的友元只能通过 ADL 可见，而非无条件地在外围作用域中可见<sup>[9](https://flylib.com/books/en/3.401.1.86/1/)</sup>。Boost.Operators 最初使用了这一技巧<sup>[8](https://www.yuzhang.io/notes/system-design/design-pattern/crtp)</sup>，CRTP 有时会与之混淆，因为 Barton 和 Nackman 经常将两者结合使用<sup>[3](https://www.pearsonhighered.com/assets/samplechapter/0/2/0/1/0201734842.pdf)</sup>。

**自引用的标准库类型。** `std::enable_shared_from_this<Widget>` 允许对象创建一个指向自身的 `shared_ptr`；派生类名出现在其自身基类的模板参数列表中，该模式将派生类名纳入 `shared_from_this` 的返回类型<sup>[1](https://en.cppreference.com/cpp/language/crtp)</sup><sup> • </sup><sup>[7](https://www.club.cc.cmu.edu/~ajo/disseminate/book.pdf)</sup>。

## 性能

基准测试结果反映了这一点。一项在 GCC 12.2 上跨优化级别比较运行时多态、CRTP 和 C++20 概念的研究发现，虚函数在所有优化级别上始终最慢，且对于复杂计算差距更大，而 CRTP 始终是最快的方法，尤其在 `-O2` 下优于另外两种方案；概念在 `-O3` 下表现与 CRTP 相似，但在 `-O2` 下明显更慢<sup>[10](https://github.com/duanegoodner/dispatch-model-benchmarks)</sup>。另一项测量报告称，在相同工作负载下 CRTP 的速度是虚函数的 1.50 倍<sup>[11](https://sagardesd.github.io/Cpp-ebook/crtp_guide.html)</sup>，第三项在分派基准测试中发现 CRTP 的性能约为虚函数的 2 倍、`std::variant` 的约 3 倍<sup>[12](https://www.linkedin.com/pulse/cptr-vs-getif-virtual-func-who-win-elhassan-abdou-mbksf)</sup>。在某些设计中 CRTP 的编译速度也可以快于虚分派，因为模板只实例化每个翻译单元所需的内容，而虚类需要在每个调用点可见完整定义以确定虚表布局<sup>[13](https://shubhankar-gambhir.github.io/posts/four-ways-to-dispatch-a-runtime-selected-strategy-in-cpp/)</sup>。

代价是分派灵活性。

## 陷阱

**错误的派生类型。** 如果两个类派生自同一个 CRTP 基类，但其中一个传入了错误的模板参数，基类将转换为错误的类，行为未定义<sup>[2](https://www.fluentcpp.com/2017/05/12/curiously-recurring-template-pattern/)</sup>。Marek Kurdej 提出的一种广泛使用的防护措施是给基类一个私有构造函数并声明 `friend T;`：派生类构造函数必须调用基类构造函数，只有友元可以访问它，不匹配的派生将编译失败<sup>[2](https://www.fluentcpp.com/2017/05/12/curiously-recurring-template-pattern/)</sup>。cppreference 的示例使用相关的 `protected` 构造函数来禁止创建独立的 `Base` 对象，否则将是未定义行为<sup>[1](https://en.cppreference.com/cpp/language/crtp)</sup>。

**不完整类型。** 在解析基类体时派生类型是不完整的，因此在成员函数定义之外访问 `Derived` 无法编译；成员函数可能需要 `auto` 返回类型，或需要一个额外的模板参数来携带 `value_type` 等类型<sup>[5](https://www.foonathan.net/2021/10/crtp-interface/)</sup>。

**名称隐藏与切片。** 派生类中的方法会隐藏同名的非虚基类方法，因此基类和派生类中的同名方法需要小心处理<sup>[2](https://www.fluentcpp.com/2017/05/12/curiously-recurring-template-pattern/)</sup>。

## C++23 推导 this

C++23 的显式对象参数由 P0847 规定，称为推导 `this`，它用关键字 `this` 显式标记对象参数，并让编译器从调用表达式推导其类型<sup>[6](https://devblogs.microsoft.com/cppblog/cpp23-deducing-this/)</sup>。它启用的特性中包括一种不要求基类以派生类为模板参数的 CRTP 版本<sup>[6](https://devblogs.microsoft.com/cppblog/cpp23-deducing-this/)</sup>：

```cpp
struct Base { void name(this auto&& self) { self.impl(); } };
struct D1 : public Base { void impl() { /* …… */ } };
```

提案作者指出，一旦 CRTP 设计变得更加复杂，复杂度会迅速增加，而推导 `this` 形式的复杂度则保持较低；[建造者模式](https://www.edgepedia.org/zh/builder-pattern)是他们给出的示例，替代了一个 CRTP 基类，其链式方法必须有条件地返回派生类型<sup>[14](https://open-std.org/jtc1/sc22/wg21/docs/papers/2019/p0847r2.html)</sup>。实用建议是：对于分派场景优先使用推导 `this`，而在基类确实需要将 `Derived` 作为类型使用时保留 CRTP，例如需要每个派生类各自的静态成员、类型依赖于 `Derived` 的成员，或返回类型为 `Derived&` 的情况<sup>[4](https://mreid-consulting.github.io/cpp-lessons/lessons/23a-crtp-and-static-polymorphism.html)</sup>。

## References

1. [Curiously Recurring Template Pattern, cppreference.com](https://en.cppreference.com/cpp/language/crtp)
2. [The Curiously Recurring Template Pattern (CRTP), Fluent C++](https://www.fluentcpp.com/2017/05/12/curiously-recurring-template-pattern/)
3. [Vandevoorde, David, and Josuttis, Nicolai (2002). C++ Templates, Chapter 16, Addison-Wesley (sample chapter)](https://www.pearsonhighered.com/assets/samplechapter/0/2/0/1/0201734842.pdf)
4. [CRTP and Static Polymorphism, M. Reid Consulting C++ lessons](https://mreid-consulting.github.io/cpp-lessons/lessons/23a-crtp-and-static-polymorphism.html)
5. [Tutorial: the CRTP Interface Technique, foonathan.net](https://www.foonathan.net/2021/10/crtp-interface/)
6. [Sy Brand (2022). C++23's Deducing this: what it is, why it is, how to use it, Microsoft C++ Team Blog](https://devblogs.microsoft.com/cppblog/cpp23-deducing-this/)
7. [A. J. Offutt et al., C++ textbook chapter on smart pointers and CRTP, CMU](https://www.club.cc.cmu.edu/~ajo/disseminate/book.pdf)
8. [CRTP (Curiously Recurring Template Pattern), Yu Zhang course notes](https://www.yuzhang.io/notes/system-design/design-pattern/crtp)
9. [Vandevoorde, David, and Josuttis, Nicolai. C++ Templates, Section 11.7: The Barton-Nackman Trick](https://flylib.com/books/en/3.401.1.86/1/)
10. [duanegoodner, dispatch-model-benchmarks: runtime vs. compile-time polymorphism benchmarks, GitHub](https://github.com/duanegoodner/dispatch-model-benchmarks)
11. [CRTP (Curiously Recurring Template Pattern) guide, Sagar Desd](https://sagardesd.github.io/Cpp-ebook/crtp_guide.html)
12. [Elhassan Abdou, CRTP vs get_if vs virtual func benchmark, LinkedIn](https://www.linkedin.com/pulse/cptr-vs-getif-virtual-func-who-win-elhassan-abdou-mbksf)
13. [Shubhankar Gambhir, Four Ways to Dispatch a Runtime-Selected Strategy in C++](https://shubhankar-gambhir.github.io/posts/four-ways-to-dispatch-a-runtime-selected-strategy-in-cpp/)
14. [Ažman, Gašper, Brand, Simon, Deane, Ben, Revzin, Barry (2019). P0847R2: Deducing this, WG21](https://open-std.org/jtc1/sc22/wg21/docs/papers/2019/p0847r2.html)

---
*Initially written Sep 17, 2026 · Reviewed: Oct 15, 2026 · Edited: Oct 15, 2026 · Last review: Oct 15, 2026*

Topic: 技术与人造世界 › 计算技术与数字系统 › 软件与编程 › Programming languages › Programming language concepts

Copyright 2026 Edgepedia

License: Edgepedia Community License 1.0, https://www.edgepedia.org/edgepedia/license

Source: https://www.edgepedia.org/zh/curiously-recurring-template-pattern

English original: https://www.edgepedia.org/curiously-recurring-template-pattern
