中文 | English |
1. 模板基础 | 1. Template Basics |
– 模板是泛型编程的核心机制,实现代码复用。 | – Templates enable generic programming, facilitating code reuse. |
– 模板函数和模板类允许类型参数化。 | – Template functions and classes allow parameterization by types. |
– 语法示例: | – Syntax example: |
“`cpp | “`cpp |
template<typename T> | template<typename T> |
T max(T a, T b) { return a > b ? a : b; } | T max(T a, T b) { return a > b ? a : b; } |
“` | “` |
| |
2. 模板函数 | 2. Template Functions |
– 支持函数重载和模板重载,根据参数类型自动推导。 | – Support function overloading and template overloading, with automatic type deduction. |
– 支持非类型模板参数,如整数、指针等。 | – Support non-type template parameters like integers, pointers, etc. |
| |
3. 模板类 | 3. Template Classes |
– 类模板参数化类型,实现通用数据结构。 | – Class templates parameterize types for generic data structures. |
– 示例: | – Example: |
“`cpp | “`cpp |
template<typename T> | template<typename T> |
class Container { | class Container { |
T value; | T value; |
public: | public: |
Container(T v) : value(v) {} | Container(T v) : value(v) {} |
T get() { return value; } | T get() { return value; } |
}; | }; |
“` | “` |
| |
4. 模板特化 | 4. Template Specialization |
– 全特化:为特定类型提供特殊实现。 | – Full specialization: provide special implementation for specific types. |
– 偏特化(仅类模板支持):针对部分模板参数做特殊处理。 | – Partial specialization (only class templates): specialize some template parameters. |
| |
5. 现代C++对模板的增强 | 5. Modern C++ Enhancements to Templates |
– 自动类型推导(C++11):使用auto和decltype简化模板代码。 | – Type deduction (C++11): use auto and decltype to simplify template code. |
– 别名模板(C++11):使用using定义模板别名。 | – Alias templates (C++11): use using to create template aliases. |
– 可变参数模板(C++11):支持任意数量模板参数,实现模板元编程。 | – Variadic templates (C++11): support arbitrary number of template parameters. |
– constexpr 与模板结合(C++11及以后):编译期计算,提高性能。 | – constexpr with templates (C++11+): enable compile-time computation. |
– 概念(Concepts,C++20):定义模板参数约束,提升模板代码可读性和安全性。 | – Concepts (C++20): constrain template parameters for readability and safety. |
| |
6. 可变参数模板示例 | 6. Variadic Template Example |
“`cpp | “`cpp |
template<typename T> | template<typename T> |
void print(T t) { std::cout << t << std::endl; } | void print(T t) { std::cout << t << std::endl; } |
| |
template<typename T, typename… Args> | template<typename T, typename… Args> |
void print(T t, Args… args) { | void print(T t, Args… args) { |
std::cout << t << “, “; | std::cout << t << “, “; |
print(args…); | print(args…); |
} | } |
“` | “` |
| |
7. 概念(Concepts)示例(C++20) | 7. Concepts Example (C++20) |
“`cpp | “`cpp |
template<typename T> requires std::integral<T> | template<typename T> requires std::integral<T> |
T add(T a, T b) { return a + b; } | T add(T a, T b) { return a + b; } |
“` | “` |