Introduction

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>.

Syntax

Remarks

The word template is a keyword with five different meanings in the C++ language, depending on the context.

  1. 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; }
    
  2. 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);
    }
    
  3. 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