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&);