Chapter 16 Templates and Generic Programming

本文详细阐述了C++中模板的基本概念、定义方法及使用技巧,包括模板参数、类型参数与非类型参数的声明与作用,展示了如何利用模板实现泛型编程,提升代码复用性和灵活性。

Generic programming involves writing code in a way that is independent of any particular type.Templates are the foundation of generic programming.Generic programming lets us write classes and functions that are polymorphic across unrelated types at compile time.

    

16.1 -- Template Definitions

A function template is a type-independent function that is used as a formula for generating a type-specific version of the function.

A template definition starts with the keyword template followed by a template parameter list, which is a comma-separated list of one or more template parameters bracketed by the less-than (<) and greater-than (>) tokens.


A template parameter can be a type parameter, which represents a type, or a nontype parameter, which represents a constant expression. A nontype parameter is declared following a type specifier.A type parameter is defined following the keyword class or typename. 

When we use a function template, the compiler infers what template argument(s) to bind to the template parameter(s). Once the compiler determines the actual template argument(s), it instantiates an instance of the function template for us.

In contrast to calling a function template, when we use a class template, we must explicitly specify arguments for the template parameters:
     Queue<int> qi;                 // Queue that holds ints
     Queue< vector<double> > qc;    // Queue that holds vectors of doubles
     Queue<string> qs;              // Queue that holds strings

Type parameters consist of the keyword class or the keyword typename followed by an identifier. In a template parameter list, these keywords have the same meaning: 
They indicate that the name that follows represents a type.

In a function template parameter list, the keywords typename and class have the same meaning and can be used interchangeably. Both keywords can be used in the same template parameter list:
     // ok: no distinction between typename and class in template parameter list
     template <typename T, class U> calc (const T&, const U&);













### 泛型编程的概念与实现方法 泛型编程(Generic Programming)是一种编程范式,其核心思想是通过编写通用的算法和数据结构来支持多种类型的操作,而无需为每种类型单独实现代码。这种方法可以显著提高代码的复用性和可维护性。在 C++ 中,泛型编程主要通过模板(Templates)机制实现[^1]。 #### 概念 在泛型编程中,抽象数据类型(ADT)的概念被进一步扩展。程序员不再局限于为单一类型定义接口,而是描述一组具有共同接口和语义行为的类型集合。这种集合被称为 **概念**(Concept)。任何满足特定算法需求的类型都可以被视为该概念的一个实例。因此,基于泛型风格构建的算法可以适用于所有满足算法要求的类型[^1]。 #### 实现方法 C++ 提供了模板机制来支持泛型编程。模板允许程序员定义函数模板和类模板,这些模板可以在编译时生成针对不同类型的代码。以下是一个简单的函数模板示例: ```cpp template <typename T> T max(T a, T b) { return (a > b) ? a : b; } ``` 在这个例子中,`max` 函数可以接受任意类型 `T` 的参数,只要该类型支持大于运算符(`>`)。这体现了泛型编程的核心思想:将具体类型替换为通用类型,从而实现代码的重用。 对于更复杂的场景,可以结合约束条件(Constraints)或概念(Concepts)来限制模板参数的范围。例如,在 C++20 中引入了概念的支持,使得模板参数的约束更加清晰和直观: ```cpp #include <concepts> template <std::integral T> T add(T a, T b) { return a + b; } ``` 在这里,`std::integral` 是一个内置概念,表示模板参数 `T` 必须是整数类型。如果尝试使用非整数类型调用此函数,则会导致编译错误。 #### 优势 泛型编程的主要优势包括: - **代码复用性**:通过编写通用代码,减少重复劳动。 - **类型安全性**:模板参数的类型检查发生在编译期,避免运行时错误。 - **性能优化**:模板代码在编译时展开,通常不会带来额外的运行时开销[^1]。 #### 示例应用 假设需要实现一个通用的排序函数,它可以对任何支持比较操作的类型进行排序: ```cpp #include <vector> #include <algorithm> #include <iostream> template <typename T> void sort_vector(std::vector<T>& vec) { std::sort(vec.begin(), vec.end()); } int main() { std::vector<int> int_vec = {5, 3, 8, 6}; sort_vector(int_vec); for (const auto& val : int_vec) { std::cout << val << " "; } std::cout << std::endl; std::vector<std::string> str_vec = {"banana", "apple", "cherry"}; sort_vector(str_vec); for (const auto& val : str_vec) { std::cout << val << " "; } std::cout << std::endl; return 0; } ``` 上述代码展示了如何使用模板函数对不同类型(如 `int` 和 `std::string`)的容器进行排序。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值