Chapter Summary
小结
Templates are a distinctive feature of C++ and are fundamental to the library. A template is a type-independent blueprint that the compiler uses to generate a variety of type-specific instances. We write the template once, and the compiler instantiates the template for the type or types with which we use the template. We can write both function templates and class templates.
模板是 C++ 语言与众不同的特性,是标准库的基础。模板是独立于类型的蓝图,编译器可以用它产生多种特定类型实例。我们只需编写一次模板,编译器将为使用模板的不同类型实例化模板。既可以编写函数模板又可以编写类模板。
Function templates are the base on which the algorithms library is built. Class templates are the base on which the library container and iterator types are built.
函数模板是建立算法库的基础,类模板是建立标准库容器和迭代器类型基础。
Compiling templates requires assistance from the programming environment. The language defines two broad strategies for instantiating templates: the inclusion model and the separate compilation model. These models have impacts on how we build our systems in so far as they dictate whether template definitions go in header files or source files. At this time, all compilers implement the inclusion model, while only some implement the separate compilation model. Your compiler's user's guide should specify how your system manages templates.
编译模板需要编程环境的支持。语言为实例化模板定义了两个主要策略:包含模型和分别编译模型。这些模型规定了模板定义应该放在头文件还是源文件中,就此而言,它们影响着构建系统的方式。现在,所有编译器实现了包含模型,只有一些编译器实现了分别编译模型。编译器的用户指南应该会说明系统怎样管理模板。
An explicit template argument lets us fix the type or value of one or more template parameters. Explicit arguments are useful in letting us design functions in which a template type need not be inferred from a corresponding argument and lets us allow conversions on the arguments.
显式模板实参使我们能够固定一个或多个模板形参的类型或值。显式实参使我们能够设计无需从对应实参推断模板类型的函数,也使我们能够对实参进行转换。
A template specialization is a specialized definition that defines a distinct version of the template that binds one or more parameters to specified types or values. Specializations are useful when there are types for which the default template definition does not apply.
模板特化是一种特化的定义,它定义了模板的不同版本,将一个或多个形参绑定到特定类型或特定值。对于默认模板定义不适用的类型,特化非常有用。
|