Classes, functions, and (since C++14) variables can be templated. A template is a piece of code with some free parameters that will become a concrete class, function, or variable when all parameters are specified. Parameters can be types, values, or themselves templates. A well-known template is std::vector
, which becomes a concrete container type when the element type is specified, e.g., std::vector<int>
.
template < *template-parameter-list* > *declaration*
export template < *template-parameter-list* > *declaration*
/* until C++11 */template <> *declaration*
template *declaration*
extern template *declaration*
/* since C++11 */template < *template-parameter-list* > class …(*opt*) *identifier*(*opt*)
template < *template-parameter-list* > class *identifier*(*opt*) = *id-expression*
template < *template-parameter-list* > typename …(*opt*) *identifier*(*opt*)
/* since C++17 */template < *template-parameter-list* > typename *identifier*(*opt*) = *id-expression*
/* since C++17 */postfix-expression* . template *id-expression*
postfix-expression* -> template *id-expression*
nested-name-specifier* template *simple-template-id* ::
The word template
is a keyword with five different meanings in the C++ language, depending on the context.
When followed by a list of template parameters enclosed in <>
, it declares a template such as a class template, a function template, or a partial specialization of an existing template.
template <class T>
void increment(T& x) { ++x; }
When followed by an empty <>
, it declares a an explicit (full) specialization.
template <class T>
void print(T x);
template <> // <-- keyword used in this sense here
void print(const char* s) {
// output the content of the string
printf("%s\\n", s);
}
When followed by a declaration without <>
, it forms an explicit instantiation declaration or definition.
template <class T>
std::set<T> make_singleton(T x) { return std::set<T>(x); }
template std::set<int> make_singleton(int x); // <-- keyword used in this sense here