# 模板（C++）

模板是C++语言中的一种实体，它定义了一族类、函数、类型别名、变量或概念，由一个或多个模板参数进行参数化，使编译器能够为每一组实际使用的实参生成具体的代码。模板是该语言实现泛型编程的机制，也是C++标准库（包括[标准模板库](https://www.edgepedia.org/zh/standard-template-library)STL）的基础。

| 关键事实 | 详情 |
|---|---|
| 模板定义的内容 | 一族类（类模板）、一族函数（函数模板）、一族类型的别名（C++11）、一族变量（C++14）或一个概念（C++20）<sup>[1](https://en.cppreference.com/cpp/language/templates)</sup> |
| 参数种类 | 类型模板参数、非类型模板参数和模板模板参数<sup>[1](https://en.cppreference.com/cpp/language/templates)</sup> |
| 特化 | 类模板、变量模板（自C++14起）和函数模板允许全特化；只有类模板和变量模板允许偏特化<sup>[1](https://en.cppreference.com/cpp/language/templates)</sup> |
| 编译模型 | 在实例化之前不编译任何内容；每一组不同的实参产生一个独立的具体实体，来自不同翻译单元的相同实例化在链接时合并<sup>[1](https://en.cppreference.com/cpp/language/templates)</sup><sup> • </sup><sup>[11](https://learn.microsoft.com/en-us/cpp/cpp/source-code-organization-cpp-templates?view=msvc-170)</sup> |
| 历史 | 于20世纪80年代末加入，并记录在《The Annotated C++ Reference Manual》中；基于模板的STL于1994年底提交至标准委员会，并在C++98中标准化<sup>[5](https://www.stroustrup.com/bs_faq.html)</sup><sup> • </sup><sup>[6](https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2003/n1426.pdf)</sup><sup> • </sup><sup>[7](https://subscription.packtpub.com/book/programming/9781803243450/2/ch02lvl1sec06/a-brief-history-of-templates)</sup> |
| 约束 | 自C++20起，概念对模板参数施加编译期约束，改善可读性、编译时间和错误信息<sup>[16](https://isocpp.org/blog/2021/05/cpp20-concepts-a-quick-introduction-bartlomiej-filipek)</sup> |
| 最新的相关特性 | 包索引（C++26）提供对参数包元素的直接按索引访问，特性测试宏为 `__cpp_pack_indexing` = 202311L<sup>[15](https://en.cppreference.com/cpp/language/pack_indexing)</sup> |

## 模板与参数的种类

`template` 关键字引入一个参数列表，后接一个声明。参数可以是类型（`class T` 或 `typename T`）、非类型值如整数或指针（`template<int N>`），或其他模板（`template<template<class> class X>`）；自C++11起，其中任何一种都可以是参数包，即零个或多个实参的列表，通过包展开、`sizeof...` 以及自C++17起的折叠表达式来处理<sup>[1](https://en.cppreference.com/cpp/language/templates)</sup>。

当提供模板实参时，或者对于函数模板以及自C++17起的类模板，从调用处推导出实参时，它们被替换到参数上，得到一个特化，即一个具体的类型或函数<sup>[1](https://en.cppreference.com/cpp/language/templates)</sup>。函数模板实参推导是最常见的情形：对两个 `int` 值调用一个 `max` 风格的模板会推导出 `T = int`，无需程序员写出<sup>[3](https://en.cppreference.com/cpp/language/function_template)</sup>。

## 实例化与包含模型

编译器不为模板本身生成任何目标代码。当某个特化在需要完整类型或函数定义的上下文中被引用时，模板被实例化，即该特化的代码被实际编译，除非它已经被显式特化或显式实例化<sup>[1](https://en.cppreference.com/cpp/language/templates)</sup>。实例化一个类模板不会实例化其成员函数，除非它们被使用<sup>[1](https://en.cppreference.com/cpp/language/templates)</sup>。

**为什么模板放在头文件中。** 由于定义必须在隐式实例化点可见，模板库通常将所有定义放在头文件中；大多数Boost库正是因此采用仅头文件形式<sup>[1](https://en.cppreference.com/cpp/language/templates)</sup>。微软的指南描述了两种标准替代方案：包含模型，即成员定义放在头文件中，每个包含它的翻译单元都编译它们；以及显式实例化模型，即库作者在 `.cpp` 文件中列出允许的实例化，这加快了编译速度，但将使用限制在这些预先启用的类型上<sup>[11](https://learn.microsoft.com/en-us/cpp/cpp/source-code-organization-cpp-templates?view=msvc-170)</sup>。在链接时，不同翻译单元生成的相同实例化被合并<sup>[1](https://en.cppreference.com/cpp/language/templates)</sup>。

## 特化与重载

特化让库能够为特定实参提供不同的实现。全特化固定所有实参，如经典的 `is_void` 特征：主模板派生自 `std::false_type`，而 `void` 特化派生自 `std::true_type`<sup>[2](https://en.cppreference.com/cpp/language/template_specialization)</sup>。偏特化对部分实参加以限制，例如匹配所有指针类型 `T*`；它只允许用于类模板和变量模板，不适用于函数模板<sup>[1](https://en.cppreference.com/cpp/language/templates)</sup>。

函数模板则依赖重载。非模板函数始终不同于具有相同类型的模板特化，而不同函数模板的特化即使签名相同也仍然不同；当一个调用匹配多个函数模板时，偏序规则选出最佳匹配<sup>[3](https://en.cppreference.com/cpp/language/function_template)</sup>。成员模板有其自身的规则：成员函数模板不能是虚函数，也不能覆盖基类的虚函数，析构函数和拷贝构造函数不能是模板<sup>[4](https://en.cppreference.com/cpp/language/member_template)</sup>。

## 约束与概念

在C++20之前，对模板实参的要求只能通过使用来表达：缺少所需操作的实参会在模板体深处失败，产生冗长的诊断信息。C++20引入的概念是模板实参上的具名编译期谓词，用 `requires` 子句或缩写语法如 `template<C1 T>` 书写<sup>[1](https://en.cppreference.com/cpp/language/templates)</sup>。它们改善了泛型代码的可读性，加快了编译速度，并给出更好的错误信息<sup>[16](https://isocpp.org/blog/2021/05/cpp20-concepts-a-quick-introduction-bartlomiej-filipek)</sup>。这一想法由来已久：STL的文档早已将输入迭代器（Input Iterator）等概念描述为具名的类型要求集合，尽管当时还无法在程序中声明概念<sup>[8](https://stl.boost.org/stl_introduction.html)</sup>。

## 与Java和C#泛型的比较

Java和C#的泛型与C++模板都将代码参数化于类型之上，但它们解析参数化的方式不同。Java采用类型擦除：类型参数被替换为其上界或 `Object`，不会为参数化类型创建新类，泛型不产生运行时开销<sup>[9](https://www.skillveris.com/interview-questions/object-oriented-programming/generics-vs-templates)</sup><sup> • </sup><sup>[10](https://docs.oracle.com/javase/tutorial/java/generics/erasure.html)</sup>。C++则为每个使用的不同类型实例化一份完全独立的具体代码副本，因此 `Stack<int>` 和 `Stack<std::string>` 是两个完全独立的已编译类<sup>[9](https://www.skillveris.com/interview-questions/object-oriented-programming/generics-vs-templates)</sup>。

这一差异解释了若干能力差距。模板接受非类型参数，允许显式和偏特化，允许类型参数用作基类，并支持模板模板参数，而C++/CLI的泛型均不允许这些<sup>[12](https://learn.microsoft.com/en-us/cpp/extensions/generics-and-templates-visual-cpp?view=msvc-170)</sup>。代价则相反：逐类型实例化产生更大的二进制文件和更慢的编译速度<sup>[9](https://www.skillveris.com/interview-questions/object-oriented-programming/generics-vs-templates)</sup>。

## 编译期计算与表达式模板

模板实例化无意中成为了一种计算机制。由于实例化是对类型和值的编译期过程，C++可以被视为一种两级语言，其中类型是一等值，模板实例化类似于一个离线部分求值器<sup>[13](https://arxiv.org/abs/cs/9810010)</sup>。这种模板元编程在很大程度上是原始模板设施的设计者未曾预料的<sup>[6](https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2003/n1426.pdf)</sup>。

**表达式模板**将同样的机制应用于性能。在Eigen线性代数库中，算术运算符不计算任何东西；它们返回存储操作数引用的小型表达式对象，因此 `3*b + 4*c + 5*d` 的完整类型在编译期编码了整棵表达式树。赋值随后生成单个融合循环，避免临时向量，并允许展开和向量化<sup>[14](https://libeigen.gitlab.io/eigen/docs-master/TopicEigenExpressionTemplates.html)</sup>。然而，SIAM对几代表达式模板框架的分析发现，并非所有实现都能为稠密和稀疏线性代数提供高性能，并引入了“智能”表达式模板的概念，将性能与领域特定语言的易用性结合起来<sup>[17](https://epubs.siam.org/doi/10.1137/110830125)</sup>。

## 实践中的成本

主要成本是编译时间、二进制大小和诊断信息。在微软Build Insights的一个示例中，单个结构体的两个模板实例化占了一次构建时间的79%，将触发这些实例化的定义移入一个源文件后，构建时间从4.966秒降至3.152秒<sup>[18](https://learn.microsoft.com/en-us/cpp/build-insights/tutorials/build-insights-template-view?view=msvc-170)</sup>。推荐的缓解措施包括移除未使用的模板、将实例化移至源文件、优先使用 `if constexpr` 而非SFINAE，以及避免呈指数增长的递归实例化模式<sup>[18](https://learn.microsoft.com/en-us/cpp/build-insights/tutorials/build-insights-template-view?view=msvc-170)</sup>。

使用数据修正了模板作为通用复用工具的印象。一项2020年的实证研究考察了50个开源系统的1267个修订版本，总计5.66亿行C++代码，发现模板确实防止了代码重复，但这种收益很大程度上局限于少数高频使用的模板，模板使用遵循幂律分布，且开发者很少通过奇异递归模板模式将动态多态转换为静态多态<sup>[19](https://eurekamag.com/research/102/828/102828930.php)</sup>。

## 近期演进

模板特性继续按照三年标准周期到来。C++26增加了包索引，使代码能够直接按指定索引访问参数包的元素，取代递归的“剥掉一个元素”模式；其特性测试宏为 `__cpp_pack_indexing`，值为202311L，而针对模板名称的进一步扩展目标为C++29<sup>[15](https://en.cppreference.com/cpp/language/pack_indexing)</sup>。当前的ISO标准是C++23，发布为[ISO/IEC 14882](https://www.edgepedia.org/zh/iso-iec-14882):2024<sup>[20](https://isocpp.org/std/the-standard)</sup>。

## References

1. [Templates, cppreference.com](https://en.cppreference.com/cpp/language/templates)
2. [Explicit (full) template specialization, cppreference.com](https://en.cppreference.com/cpp/language/template_specialization)
3. [Function template, cppreference.com](https://en.cppreference.com/cpp/language/function_template)
4. [Member templates, cppreference.com](https://en.cppreference.com/cpp/language/member_template)
5. [Bjarne Stroustrup: FAQ](https://www.stroustrup.com/bs_faq.html)
6. [N1426: A history of templates (C++ standards committee, 2003)](https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2003/n1426.pdf)
7. [A Brief History of Templates, Template Metaprogramming with C++ (Packt)](https://subscription.packtpub.com/book/programming/9781803243450/2/ch02lvl1sec06/a-brief-history-of-templates)
8. [The Standard Template Library: Introduction (SGI)](https://stl.boost.org/stl_introduction.html)
9. [Generics vs Templates: Java vs C++ Guide, SkillVeris](https://www.skillveris.com/interview-questions/object-oriented-programming/generics-vs-templates)
10. [Type Erasure, The Java Tutorials, Oracle](https://docs.oracle.com/javase/tutorial/java/generics/erasure.html)
11. [Source code organization (C++ Templates), Microsoft Learn](https://learn.microsoft.com/en-us/cpp/cpp/source-code-organization-cpp-templates?view=msvc-170)
12. [Generics and Templates (C++/CLI), Microsoft Learn](https://learn.microsoft.com/en-us/cpp/extensions/generics-and-templates-visual-cpp?view=msvc-170)
13. [C++ Templates as Partial Evaluation (arXiv cs/9810010)](https://arxiv.org/abs/cs/9810010)
14. [Expression templates in Eigen](https://libeigen.gitlab.io/eigen/docs-master/TopicEigenExpressionTemplates.html)
15. [Pack indexing (since C++26), cppreference.com](https://en.cppreference.com/cpp/language/pack_indexing)
16. [C++20 Concepts - a Quick Introduction, Standard C++](https://isocpp.org/blog/2021/05/cpp20-concepts-a-quick-introduction-bartlomiej-filipek)
17. [Expression Templates Revisited: A Performance Analysis of Current Methodologies, SIAM Journal on Scientific Computing](https://epubs.siam.org/doi/10.1137/110830125)
18. [Troubleshoot template instantiation impact on build time, Microsoft Learn](https://learn.microsoft.com/en-us/cpp/build-insights/tutorials/build-insights-template-view?view=msvc-170)
19. [How C++ templates are used for generic programming: An empirical study on 50 open source systems, ACM TOSEM 29(1), 2020](https://eurekamag.com/research/102/828/102828930.php)
20. [The Standard, Standard C++ (isocpp.org)](https://isocpp.org/std/the-standard)

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

Topic: 技术与人造世界 › 计算技术与数字系统 › 软件与编程 › Programming languages › Individual programming languages › C-family and imperative languages

Copyright 2026 Edgepedia

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

Source: https://www.edgepedia.org/zh/template-c

English original: https://www.edgepedia.org/template-c
