C++ Tutorial · Object-Oriented C++ · Lesson 14 of 21

C++ Templates

Function and class templates, and C++20 concepts.

Templates

Templates generate code for each type you use — the foundation of the standard library (std::vector<T>, std::sort):

Example 1
#include <concepts>
#include <iostream>
#include <string>
#include <vector>

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

template <typename A, typename B>
struct Pair {
    A first;
    B second;
};

template <typename T>
    requires std::integral<T> || std::floating_point<T>
T sum(const std::vector<T>& values) {
    T total{};
    for (const T& v : values) total += v;
    return total;
}

int main() {
    std::cout << maxOf(3, 9) << ' ' << maxOf(2.5, 1.5) << ' ' << maxOf<std::string>("pear", "apple") << '\n';
    Pair<std::string, int> p{"age", 36};
    std::cout << p.first << '=' << p.second << '\n';
    std::cout << sum(std::vector<int>{1, 2, 3}) << ' ' << sum(std::vector<double>{1.5, 2.25}) << '\n';
}

Output

9 2.5 pear
age=36
6 3.75

Run this on your computer — see “Get Started” for setup.

Concepts (C++20)

Concepts constrain template parameters with readable requirements and much clearer error messages.

Test yourself

What C++20 feature constrains template parameters with named requirements?

  1. Macros
  2. Concepts
  3. Interfaces
  4. Traits only
Show answer

Answer: Concepts