`template` — C++ Keyword

`template` — C++ Keyword

The template keyword in C++: defines generic functions, classes, variables, and alias templates.

How to use this reference page

Use reference pages to confirm names, categories, nearby facilities, and the constraints that matter before writing or reviewing code.

  • Scan the top of the page first to identify the primary types, functions, or algorithm families involved.
  • Use the nearby-page links when your question is really about a companion header, related algorithm family, or broader subsystem.
  • Validate tricky behavior with a small compileable example before relying on memory for details like invalidation, ordering, allocation, or lifetime rules.

template

Introduces a template, enabling generic programming. Templates are instantiated by the compiler for each unique set of template arguments.

Syntax

template <parameter-list> declaration

// Explicit instantiation
template class Name<Args>;

// Explicit specialization
template <> class Name<SpecificType> { ... };

Example

#include <print>

// Function template
template <typename T>
T max_of(T a, T b) {
    return a > b ? a : b;
}

// Class template
template <typename T, int N>
class FixedArray {
    T data_[N]{};
public:
    T& operator[](int i) { return data_[i]; }
    int size() const { return N; }
};

// Variable template (C++14)
template <typename T>
constexpr T pi = T(3.14159265358979);

int main() {
    std::println("{}", max_of(3, 7));          // 7
    std::println("{:.2f}", max_of(1.5, 2.8));  // 2.80

    FixedArray<int, 4> arr;
    arr[0] = 42;
    std::println("{}", arr[0]);   // 42

    std::println("{:.6f}", pi<double>);  // 3.141593
}

Notes

Example in practice

int main() {
    // Pick one facility from this reference page.
    // Write the smallest program that exercises its main precondition,
    // complexity rule, or lifetime constraint before scaling up.
    return 0;
}