Team LiB
Previous Section Next Section

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.


Team LiB
Previous Section Next Section