Skip to content
KALANBLON
Show contents

Chapter 2 of 7 · 20 min

Templates and concepts

By the end of this chapter, you'll be able to

  • Write a function template and let the compiler deduce the types
  • Write a class template and use argument deduction
  • Constrain a template with a standard concept such as std::integral
  • Define your own concept with requires

Function and class templates

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

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

template <std::integral T>
T gcd(T a, T b) {
    while (b != 0) {
        T r = a % b;
        a = b;
        b = r;
    }
    return a;
}

template <typename T>
class Pair {
public:
    Pair(T first, T second) : first_(first), second_(second) {}
    T sum() const { return first_ + second_; }

private:
    T first_;
    T second_;
};

int main() {
    std::cout << larger(3, 7) << ' ' << larger(2.5, 1.5) << ' '
              << larger(std::string("kiwi"), std::string("banana")) << '\n';
    std::cout << gcd(84, 36) << ' ' << gcd(270L, 192L) << '\n';
    Pair<double> p(1.5, 2.25);
    Pair q(10, 32);              // the type int is deduced from the arguments
    std::cout << p.sum() << ' ' << q.sum() << '\n';
}
7 2.5 kiwi
12 6
3.75 42
  • template <typename T> declares a type parameter. At each call, the compiler deduces T from the arguments (int, double, std::string) and generates the matching version: this is called instantiation.
  • larger works with any type that can be compared with <. With strings, it's alphabetical order: "kiwi" comes after "banana".
  • template <std::integral T> replaces typename with a concept: T must be an integer type. gcd accepts int and long, and refuses doubles.
  • Pair q(10, 32): since C++17, the compiler also deduces a class template's parameters from the constructor.
  • A template's code generally goes in the header: the compiler must see its complete definition to instantiate it.

With doubles, the constraint fails: the error is reported at the call, naming the concept.

Step 5 of 5
Text description of the animation
  1. The compiler meets a call to the template.
  2. It deduces T from the arguments' type.
  3. It checks the constraint: int is indeed an integer type.
  4. It generates this version's code, as if you'd written it by hand.
  5. With doubles, the constraint fails: the error is reported at the call, naming the concept.

Defining your own concept

A concept is a condition on a type, checked at compile time. requires describes the expressions the type must allow:

#include <concepts>
#include <iostream>
#include <vector>

template <typename T>
concept Measurable = requires(const T& x) {
    { x.area() } -> std::convertible_to<double>;
};

struct Square {
    double side;
    double area() const { return side * side; }
};

struct Disc {
    double radius;
    double area() const { return 3.14159 * radius * radius; }
};

template <Measurable T>
double total_area(const std::vector<T>& shapes) {
    double total = 0;
    for (const auto& s : shapes) total += s.area();
    return total;
}

int main() {
    std::vector<Square> squares{{2}, {3}};
    std::vector<Disc> discs{{1}};
    std::cout << total_area(squares) << ' ' << total_area(discs) << '\n';
}
13 3.14159

Measurable requires an area() method whose result converts to double. Square and Disc have no inheritance link: they satisfy the concept simply because they have the right method. Unlike virtual functions, everything is resolved at compile time, at no run-time cost.

Your turn

Worked exercise

Worked exercise: the generic average

Write an average template that accepts a std::vector<T> of numbers (integers or floating-point, thanks to a concept you define), returns a double, and throws std::invalid_argument if the vector is empty. Test it with ints and doubles.

Hint 1
std::integral<T> || std::floating_point<T> combines two standard concepts: you can turn it into a Number concept.
Hint 2
Convert the sum to double before dividing: the average of {1, 2} must be 1.5, not 1.
Show the solution and common mistakes
#include <concepts>
#include <iostream>
#include <stdexcept>
#include <vector>

template <typename T>
concept Number = std::integral<T> || std::floating_point<T>;

template <Number T>
double average(const std::vector<T>& values) {
    if (values.empty()) throw std::invalid_argument("average of an empty list");
    double sum = 0;
    for (T v : values) sum += static_cast<double>(v);
    return sum / static_cast<double>(values.size());
}

int main() {
    std::cout << average(std::vector<int>{1, 2}) << ' ' << average(std::vector<double>{12.5, 15.0, 9.5}) << '\n';
    try {
        average(std::vector<int>{});
    } catch (const std::invalid_argument& e) {
        std::cout << "error: " << e.what() << '\n';
    }
}
1.5 12.3333
error: average of an empty list

Common mistakes:

  • Accumulating in a variable of type T: with ints, the division is integer division and {1, 2} gives 1.
  • Forgetting the empty case: dividing by zero would give nan with no message at all.

Summary

  1. 1A template is written once; the compiler instantiates it for each type used.
  2. 2Types are deduced from the arguments, including for class templates (C++17).
  3. 3A concept expresses what a type must be able to do, checked at compile time.
  4. 4requires defines a concept from the expressions the type must allow.
  5. 5Constraining a template gives clear errors, reported where the call is.

Your progress is saved on this device. Create a free account to keep your progress on all your devices.