C/C++ Arena

Templates in C++

Function and class templates in C++, type deduction, and constraining templates with C++20 concepts.

A template is a blueprint the compiler fills in for each type you use it with. std::vector<int> and std::vector<std::string> are two different classes generated from one template.

Function templates usually deduce their types from the arguments: max_of(3, 7) uses T = int.

C++20 concepts state what a template needs, such as template <std::integral T>, which gives far clearer error messages than the old walls of template errors.

Example

#include <concepts>
#include <iostream>
#include <string>

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

template <std::integral T>
bool is_even(T n) { return n % 2 == 0; }

int main() {
    std::cout << max_of(3, 7) << " " << max_of(std::string("fig"), std::string("apple")) << " " << is_even(10) << "\n";
    return 0;
}

Output:

7 fig 1

Practice it