
Template Metaprogramming with C++
By :

So far in this chapter, we have used the general term templates. However, there are four different terms describing the kind of templates we have written:
max
template seen previously.class
, struct
, or union
keyword). An example is the vector
class we wrote in the previous section.NewLine
template from the previous section.Templates are parameterized with one or more parameters (in the examples we have seen so far, there was a single parameter). These are called template parameters and can be of three categories:
template<typename T>
, where the parameter represents a type specified when the template is used.template<size_t N>
or template<auto n>
, where each parameter must have a structural type, which includes integral types, floating-point types (as for C++20), pointer types, enumeration types, lvalue reference types, and others.template<typename K, typename V, template<typename> typename C>
, where the type of a parameter is another template.Templates can be specialized by providing alternative implementations. These implementations can depend on the characteristics of the template parameters. The purpose of specialization is to enable optimizations or reduce code bloat. There are two forms of specialization:
The process of generating code from a template by the compiler is called template instantiation. This happens by substituting the template arguments for the template parameters used in the definition of the template. For instance, in the example where we used vector<int>
, the compiler substituted the int
type in every place where T
appeared.
Template instantiation can have two forms:
vector<int>
and vector<double>
, it will instantiate the vector
class template for the types int
and double
and nothing more.All the terms and topics mentioned in this section will be detailed in other chapters of the book. This section is intended as a short reference guide to template terminology. Keep in mind though that there are many other terms related to templates that will be introduced at the appropriate time.