Class templates, lambdas, constexpr and concepts

Generic containers, functions as objects, work done at compile time, and templates that state their requirements.

What you'll learn
  • Write a class template that owns a dynamic array of any type
  • Replace a function object with a lambda, and understand captures
  • Move computation to compile time with constexpr, and constrain templates with concepts

Class templates

27class_templates.cpp combines lesson 2’s templates with lesson 6’s smart pointers:

template <typename T>
struct DynamicArray {
    int size;
    std::unique_ptr<T[]> ptr;
    DynamicArray(int new_size) : size(new_size), ptr(new T[new_size]) {}
    void fill(T value) { for (int i = 0; i < size; i++) ptr[i] = value; }
};

DynamicArray<int> and DynamicArray<double> are two different classes stamped out from one recipe; the program fills them with 5 and 1.23. It needs no destructor: the unique_ptr frees the array. This is, in miniature, how std::vector is built.

Function objects and lambdas

Algorithms such as find_if take a predicate — something callable that answers yes or no. 30function_objects.cpp writes one as a struct with operator():

struct IsDivisible {
    int divisor;
    IsDivisible(int new_divisor) : divisor(new_divisor) {}
    bool operator()(int dividend) { return dividend % divisor == 0; }
};
auto itr = std::ranges::find_if(my_vector, IsDivisible(10));   // finds 20

The object carries state (divisor) along with the behaviour. 31lambdas.cpp says the same in one expression:

auto is_divisibleby_10 = [divisor = 10](int dividend) {
    return dividend % divisor == 0;
};

A lambda is such a struct — the compiler generates it. The square brackets list what it captures: [divisor = 10] creates a member, [x] copies a local, [&x] refers to it, and [&] (used throughout lesson 13’s examples) captures everything by reference. Both programs print 1 (50 is divisible) and 20.

One caution in both: *itr is printed without checking. If nothing in the vector were divisible by 10, find_if would return end(), and dereferencing that is undefined behaviour.

constexpr

constexpr int factorial(int n) { return n <= 1 ? 1 : n * factorial(n - 1); }
constexpr int result = factorial(5);           // computed by the compiler: 120
int result2 = factorial(rd() % 6);             // computed at run time

39constexpr.cpp shows both sides of the same function. Called with a constant, it runs inside the compiler and result is baked into the binary. Called with a random number, it is an ordinary function. constexpr means can be evaluated at compile time, not must.

Concepts

An unconstrained template accepts any type and fails deep inside its body when the type does not fit, often with pages of errors. A C++20 concept states the requirement up front:

void print(std::integral auto value) { ... }
print(10);      // fine
print(1.5);     // error: the constraint std::integral<double> is not satisfied

40concepts.cpp accepts any integer type — int, long, char, bool — and rejects floating point with a one-line explanation.

Try it yourself. Write a lambda that counts how many times it has been called, using [count = 0]() mutable { return ++count; }. Call it three times. Then copy it into a second variable and call that one: does the count continue or restart? (A lambda is an object, so the copy has its own member.)

View source on GitHub →