---
title: "Templates and Generic Programming"
book: "University Computer Science — Year 2"
subject: computer-science
language: en
chapter: 4
exercises: 12
source: https://one-course.com/books/computer-science/4/en/chapter/4-templates-and-generic-programming
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 4 — Templates and Generic Programming

Last year’s dynamic array held `int`s. The weather station needs one of `double`s, the library one of titles. C offers two ways out, and the program below shows both: copy the code and change the type, or write it once for blocks of bytes, with `void *` and an element size.

```c
/* The same with void *: one copy of the code, but the types are gone. */
struct any_vec { void *data; size_t size, cap, elem; };

int any_vec_push(struct any_vec *v, const void *x)
{
    if (v->size == v->cap) {
        size_t cap = v->cap ? 2 * v->cap : 1;
        void *p = realloc(v->data, cap * v->elem);
        if (!p)
            return -1;
        v->data = p;
        v->cap = cap;
    }
    char *slot = (char *)v->data + v->size++ * v->elem;
    for (size_t i = 0; i < v->elem; i++)
        slot[i] = ((const char *)x)[i];
    return 0;
}
```

***Listing 4.1.** The array once more, for any element size, with `void *` code/bachelor-2/04-cpp-templates/listings/int_vec.c*

```
$ gcc -std=c17 -O2 -Wall -Wextra -o int_vec int_vec.c -lm && ./int_vec
ints: 1 ... 25, doubles: 0.25 ... 1.25
```

***Output 4.1.** An array of `int`, written for `int`, and an array of `double`, written for bytes.*

The first way multiplies the code: a bug fixed in the `int` version stays in the `double` one. The second keeps one copy but throws the types away: `any_vec_push` accepts the address of anything, copies bytes one by one with a loop the compiler cannot specialise, and every reader must cast `data` back to the right type, which nothing checks. The C library’s `qsort` is written the second way. C++ offers a third: write the code once, with the type as a parameter, and let the compiler write each typed copy.

**You already know.**

[Chapter 2](https://one-course.com/books/computer-science/4/en/chapter/2-copying-moving-and-smart-pointers#ch-b2-cpp-copy-move): a class that owns memory follows the [rule of five](https://one-course.com/books/computer-science/4/en/chapter/2-copying-moving-and-smart-pointers#def-b2-cpp-copy-move-rules), moves are cheap and `noexcept`, and a growing array makes fewer than $2(n-1)$ transfers when it doubles. Book 3 sorted with `qsort`, which receives the array as `void *`, the element size, and a comparison function called through a pointer.

## 4.1 Function templates

**Definition 4.1 (Function template, class template, template parameter).**

A *template* is a declaration preceded by `template <typename T, ...>`, whose *template parameters* stand for types (`typename T`) or for constant values (such as `std::size_t N`). A *function template* describes a family of functions, a *class template* a family of classes, one member of the family for each choice of the parameters.

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

int main()
{
    std::cout << larger(3, 7) << '\n';                      // T = int
    std::cout << larger(2.5, -1.0) << '\n';                 // T = double
    std::string p = "pier", q = "dunes";
    std::cout << larger(p, q) << '\n';                      // T = std::string
    std::cout << larger<double>(3, 7.5) << '\n';            // T given: 3 converts to 3.0
    // larger(3, 7.5) does not compile: T would be int and double at once
    return 0;
}
```

***Listing 4.2.** One [function template](#def-b2-cpp-templates-template), three types code/bachelor-2/04-cpp-templates/listings/max_template.cpp*

```
$ g++ -std=c++20 -O2 -Wall -Wextra -o max_template max_template.cpp && ./max_template
7
2.5
pier
7.5
```

***Output 4.2.** Each call used the version for its type.*

**Definition 4.2 (Template argument deduction).**

At a call of a [function template](#def-b2-cpp-templates-template) with no explicit arguments, the compiler finds the [template](#def-b2-cpp-templates-template) arguments by *template argument deduction*: it matches each parameter type against the type of the corresponding argument. Each [template parameter](#def-b2-cpp-templates-template) must be deduced to a single type from all the arguments in which it appears; a parameter that appears in no function parameter (only in the return type, say) cannot be deduced, and must be given explicitly, as in `larger<double>(3, 7.5)`.

Deduction does not convert: `larger(3, 7.5)` would make `T` both `int` and `double`, and the call does not compile. Given explicitly, `T = double` turns the call into an ordinary one, where 3 converts to `double`.

## 4.2 Class templates

The growable array of the opening, written once for every type, is a [class template](#def-b2-cpp-templates-template). Unlike the C version, it must also respect what a C++ element needs: a `std::string` cannot be copied byte by byte, and its [constructor](https://one-course.com/books/computer-science/4/en/chapter/1-from-c-to-c-classes-and-resource-management#def-b2-cpp-classes-raii-constructor) and [destructor](https://one-course.com/books/computer-science/4/en/chapter/1-from-c-to-c-classes-and-resource-management#def-b2-cpp-classes-raii-constructor) must run. The array therefore allocates *raw* memory (`::operator new`, the C++ form of `malloc`), builds each element in it with a *placement new*, `new (address) T(...)`, and destroys it with an explicit call to its [destructor](https://one-course.com/books/computer-science/4/en/chapter/1-from-c-to-c-classes-and-resource-management#def-b2-cpp-classes-raii-constructor).

```cpp
template <typename T>
class Vec {
public:
    Vec() = default;
    ~Vec() { clear(); ::operator delete(data_); }
    Vec(const Vec &o) : Vec()
    {
        reserve(o.size_);
        for (std::size_t i = 0; i < o.size_; i++)
            push_back(o[i]);
    }
    Vec(Vec &&o) noexcept
        : data_(std::exchange(o.data_, nullptr)), size_(std::exchange(o.size_, 0)),
          cap_(std::exchange(o.cap_, 0)) {}
    Vec &operator=(Vec o) noexcept      // copy and swap; moves when given an rvalue
    {
        std::swap(data_, o.data_);
        std::swap(size_, o.size_);
        std::swap(cap_, o.cap_);
        return *this;
    }

    void push_back(T x)                 // x is a copy or a moved value; it is moved in
    {
        if (size_ == cap_)
            reserve(cap_ ? 2 * cap_ : 1);
        new (data_ + size_) T(std::move(x));    // construct in raw memory
        size_++;
    }
private:
    T *data_ = nullptr;
    std::size_t size_ = 0, cap_ = 0;
};
```

***Listing 4.3.** `Vec<T>`: the special members, `push_back` and the data code/bachelor-2/04-cpp-templates/listings/vec.hpp*

```cpp
    void reserve(std::size_t n)
    {
        if (n <= cap_)
            return;
        T *p = static_cast<T *>(::operator new(n * sizeof(T)));   // raw memory, no T built
        std::size_t i = 0;
        try {
            for (; i < size_; i++)                  // moves if they cannot throw, else copies
                new (p + i) T(std::move_if_noexcept(data_[i]));
        } catch (...) {                          // a copy threw: undo, the old block is intact
            while (i > 0)
                p[--i].~T();
            ::operator delete(p);
            throw;
        }
        clear();
        ::operator delete(data_);
        data_ = p;
        size_ = i;
        cap_ = n;
    }
    void clear() noexcept
    {
        for (std::size_t i = size_; i > 0; i--)
            data_[i - 1].~T();          // destroy in reverse order
        size_ = 0;
    }
```

***Listing 4.4.** `reserve` and `clear` code/bachelor-2/04-cpp-templates/listings/vec.hpp*

`reserve` builds the elements in the new block before destroying the old ones. It moves them when their [move constructor](https://one-course.com/books/computer-science/4/en/chapter/2-copying-moving-and-smart-pointers#def-b2-cpp-copy-move-move) cannot throw and copies them otherwise (`std::move_if_noexcept`), so that if a copy throws the old block is still complete: the strong guarantee of [Chapter 2](https://one-course.com/books/computer-science/4/en/chapter/2-copying-moving-and-smart-pointers#ch-b2-cpp-copy-move), which `tests/vec_test.cpp` checks with an element whose fourth copy throws. The remaining members are one-liners: `operator[]`, `at`, which checks its index, `size`, `capacity`, and `begin` and `end`, which make the range-`for` work.

![The layout of every Vec<T>: three members of 24 bytes in all, whatever T, and a heap block of cap_ slots of sizeof(T) bytes, the first size_ of which hold constructed objects. The destructor destroys exactly those, then frees the block.](https://one-course.com/images/onecourse/chapters/computer-science-4/b2-cpp-templates/fig-e19f54d06fa2.svg)

*The layout of every `Vec<T>`: three members of 24 bytes in all, whatever `T`, and a heap block of `cap_` slots of `sizeof(T)` bytes, the first `size_` of which hold constructed objects. The [destructor](https://one-course.com/books/computer-science/4/en/chapter/1-from-c-to-c-classes-and-resource-management#def-b2-cpp-classes-raii-constructor) destroys exactly those, then frees the block.*

```cpp
int main()
{
    Vec<int> squares;
    Vec<double> quarters;
    Vec<std::string> streets;
    for (int i = 1; i <= 5; i++) {
        squares.push_back(i * i);
        quarters.push_back(i / 4.0);
    }
    streets.push_back("Mill Lane");
    streets.push_back("Quay Street");
    Vec<std::string> copy = streets;            // the template's copy constructor, for strings
    copy[0] = "Harbour Road";
    for (int x : squares) std::cout << x << ' ';
    std::cout << "| " << quarters[4] << " | " << streets[0] << ", " << copy[0] << '\n';
    std::cout << "sizes " << sizeof(Vec<int>) << ' '
        << sizeof(Vec<std::string>) << " bytes, capacity "
              << squares.capacity() << '\n';
    return 0;
}
```

***Listing 4.5.** One [class template](#def-b2-cpp-templates-template), three classes code/bachelor-2/04-cpp-templates/listings/vec_demo.cpp*

```
$ g++ -std=c++20 -O2 -Wall -Wextra -o vec_demo vec_demo.cpp && ./vec_demo
1 4 9 16 25 | 1.25 | Mill Lane, Harbour Road
sizes 24 24 bytes, capacity 8
```

***Output 4.3.** Integers, doubles and strings in the same code.*

**Definition 4.3 (Generic programming).**

*Generic programming* writes algorithms and data structures once, in terms of the operations they need from their element types (copy, compare, add), so that they apply to every type providing those operations, with no loss of type checking or of speed against a version written for one type.

## 4.3 Instantiation

A [template](#def-b2-cpp-templates-template) is not code. It becomes code when it is used.

**Definition 4.4 (Template instantiation).**

*Template instantiation* is the generation, by the compiler, of a function or a class from a [template](#def-b2-cpp-templates-template) and a list of [template](#def-b2-cpp-templates-template) arguments, by substituting the arguments for the parameters. A use such as `Vec<int>` or `larger(3, 7)` causes the instantiation; a [member function](https://one-course.com/books/computer-science/4/en/chapter/1-from-c-to-c-classes-and-resource-management#def-b2-cpp-classes-raii-class) of a [class template](#def-b2-cpp-templates-template) is instantiated only if it is used.

```bash
g++ -std=c++20 -O0 -c vec_demo.cpp -o vec_demo.o
nm -C vec_demo.o | grep -c ' Vec<'
nm -C vec_demo.o | grep 'push_back'
```

***Listing 4.6.** Compiling the demo and listing its symbols code/bachelor-2/04-cpp-templates/listings/instantiate.sh*

```
$ g++ -std=c++20 -O0 -c vec_demo.cpp -o vec_demo.o
$ nm -C vec_demo.o | grep -c ' Vec<'
30
$ nm -C vec_demo.o | grep 'push_back'
0000000000000000 W Vec<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >::push_back(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >)
0000000000000000 W Vec<double>::push_back(double)
0000000000000000 W Vec<int>::push_back(int)
```

***Output 4.4.** Thirty instantiated functions, among them three `push_back`s.*

`nm` lists the symbols of the object file and `-C` turns their encoded names back into C++. The three `push_back`s are three separate functions, compiled from one text for three types. Their type `W` (*weak*) tells the linker what to do when several object files contain the same instantiation, which is the normal case: every file that uses `Vec<int>` instantiates it.

**Proposition 4.5 (One instantiation per argument list).**

In each translation unit, a [template](#def-b2-cpp-templates-template) is instantiated at most once for each distinct list of [template](#def-b2-cpp-templates-template) arguments, however many times it is used with that list. When several translation units instantiate the same [template](#def-b2-cpp-templates-template) with the same arguments, the linker keeps one copy of each function. A program therefore contains at most one copy of each instantiated function per distinct argument list, and a [template](#def-b2-cpp-templates-template) used with $k$ argument lists, of which it uses $m$ [member functions](https://one-course.com/books/computer-science/4/en/chapter/1-from-c-to-c-classes-and-resource-management#def-b2-cpp-classes-raii-class) with each, yields at most $km$ functions.

**Proof.** Within a unit, the compiler records each specialisation it has generated, keyed by the [template](#def-b2-cpp-templates-template) and its arguments, and reuses the record for later uses, so a second use generates nothing. Across units, each copy is emitted as a weak symbol with the same encoded name, built from the [template](#def-b2-cpp-templates-template) and its arguments; the linker, on finding several weak definitions of one name, keeps one and discards the others, which the language allows because they are identical (they come from the same [template](#def-b2-cpp-templates-template) with the same arguments). The bound follows: at most one function for each pair of an argument list and a used member. ∎

![One template, two translation units, two argument lists. Each unit instantiates what it uses; the linker merges the two copies of Vec<int>::push_back.](https://one-course.com/images/onecourse/chapters/computer-science-4/b2-cpp-templates/fig-7292593817d2.svg)

*One [template](#def-b2-cpp-templates-template), two translation units, two argument lists. Each unit instantiates what it uses; the linker merges the two copies of `Vec<int>::push_back`.*

Two consequences follow. A [template](#def-b2-cpp-templates-template)’s definition must be visible wherever it is used, since the compiler can only instantiate what it can read: [templates](#def-b2-cpp-templates-template) live in headers ([Exercise 4.2](#exo-b2-cpp-templates-2) shows what happens otherwise). And errors in a [template](#def-b2-cpp-templates-template)’s use appear at instantiation, inside the [template](#def-b2-cpp-templates-template)’s body, as the next section shows. Some types deserve a different body from the general one; a [template](#def-b2-cpp-templates-template) can be given one.

**Definition 4.6 (Template specialisation).**

A *full specialisation* `template <> ... f<A>(...)` gives the body of a [template](#def-b2-cpp-templates-template) for one particular argument list `A`, used instead of the general body whenever those arguments are chosen. [Function templates](#def-b2-cpp-templates-template) may also be *overloaded*: a second [template](#def-b2-cpp-templates-template) with a more specific parameter (such as `T *` for `T`), chosen when it matches better.

```cpp
template <typename T>
std::string describe(const T &x) { return "value " + std::to_string(x); }

template <>                                     // the full specialisation for bool
std::string describe<bool>(const bool &x) { return x ? "yes" : "no"; }

template <typename T>
std::string describe(T *p)
    { return p ? "pointer to " + describe(*p) : "null pointer"; }  // an overload

int main()
{
    int n = 42;
    bool open = true;
    std::cout << describe(n) << " | " << describe(2.5) << " | " << describe(open) << " | "
              << describe(&n) << " | " << describe(static_cast<int *>(nullptr)) << '\n';
    return 0;
}
```

***Listing 4.7.** A general [template](#def-b2-cpp-templates-template), a specialisation and an overload code/bachelor-2/04-cpp-templates/listings/specialise.cpp*

```
$ g++ -std=c++20 -O2 -Wall -Wextra -o specialise specialise.cpp && ./specialise
value 42 | value 2.500000 | yes | pointer to value 42 | null pointer
```

***Output 4.5.** Each value described by the most specific version.*

[Templates](#def-b2-cpp-templates-template) also take values: `std::array<double, 3>` is a class with three `double`s, its size fixed at compile time. Values computed at compile time come from `constexpr` functions, which the compiler runs while it compiles when their arguments are constants.

```cpp
constexpr std::uint64_t power(std::uint64_t b, unsigned e)
{
    std::uint64_t r = 1;
    while (e--)
        r *= b;
    return r;
}

static_assert(power(2, 10) == 1024);            // checked at compile time
constexpr std::uint64_t KIB = power(2, 10), GIB = power(KIB, 3);
int table[power(3, 4)];                          // an array size must be a constant: 81

int main(int argc, char **)
{
    std::printf("%llu %llu %zu\n", (unsigned long long)GIB,
        (unsigned long long)power(argc + 1, 20),
                sizeof table / sizeof table[0]);
    return 0;
}
```

***Listing 4.8.** A function run by the compiler, and at run time code/bachelor-2/04-cpp-templates/listings/constexpr_pow.cpp*

```
$ g++ -std=c++20 -O2 -Wall -Wextra -o constexpr_pow constexpr_pow.cpp && ./constexpr_pow
1073741824 1048576 81
```

***Output 4.6.** Two compile-time values and one run-time value.*

`GIB` and the size of `table` were computed by the compiler; `power(argc + 1, 20)` depends on the command line, $2^{20}$ here, and was computed when the program ran. A `static_assert` is a test that runs at compile time: if it fails, the program does not compile.

## 4.4 Requirements on a type parameter

A [template](#def-b2-cpp-templates-template)’s body uses operations of its type parameters (`<`, copying, `+`), and so requires them. Until C++20 the requirement was unwritten: the compiler found out at instantiation, inside the body. Below, the same [function template](#def-b2-cpp-templates-template) is used with a type that has no `<`, first as it stands and then with its requirement written down.

```
no_concept.cpp: In instantiation of 'T smallest(const std::vector<T>&) [with T = Point]':
no_concept.cpp:20:23:   required from here
no_concept.cpp:12:15: error: no match for 'operator<' (operand types are 'const Point' and 'Point')
   12 |         if (x < best)
      |             ~~^~~~~~
```

***Output 4.7.** Without a stated requirement, the error is reported inside the [template](#def-b2-cpp-templates-template). Some lines are left out.*

**Definition 4.7 (Concept, constraint).**

A *concept* is a named, compile-time predicate on [template](#def-b2-cpp-templates-template) arguments, defined by `template <typename T> concept C = expression;`, where the expression may combine other concepts and `requires` expressions listing operations that must be valid. A *constraint* attaches concepts to a [template](#def-b2-cpp-templates-template), as `template <C T>` or `requires C<T>`: the [template](#def-b2-cpp-templates-template) is then considered only for arguments that satisfy them. Concepts are a C++20 feature.

```cpp
template <typename T>
concept Ordered = std::copyable<T> && requires(const T a, const T b) {
    { a < b } -> std::convertible_to<bool>;
};

template <Ordered T>
T smallest(const std::vector<T> &v)
{
    T best = v[0];
    for (const T &x : v)
        if (x < best)
            best = x;
    return best;
}
```

***Listing 4.9.** The requirement, stated in front code/bachelor-2/04-cpp-templates/listings/with_concept.cpp*

```
with_concept.cpp: In function 'int main()':
with_concept.cpp:26:23: error: no matching function for call to 'smallest(std::vector<Point>&)'
   26 |     Point p = smallest(pts);
      |               ~~~~~~~~^~~~~
with_concept.cpp:14:3: note: constraints not satisfied
with_concept.cpp:10:9: note: the required expression '(a < b)' is invalid
   10 |     { a < b } -> std::convertible_to<bool>;
      |       ~~^~~
```

***Output 4.8.** With a [concept](#def-b2-cpp-templates-concept), the error is reported at the call, naming the missing operation. Some lines are left out.*

The second message is longer but speaks to the caller: the call does not match, because `Point` does not satisfy `Ordered`, because `a < b` is invalid. The first speaks of a line inside a function the caller may never have read. In a library [template](#def-b2-cpp-templates-template) ten calls deep, the difference is between one message and a page of them. The standard library predefines many [concepts](#def-b2-cpp-templates-concept), such as `std::copyable`, `std::integral` or `std::random_access_iterator`.

**Method 4.8 (Stating requirements first).**

To write a function or [class template](#def-b2-cpp-templates-template):

1. list the operations the body will use on each type parameter, with their result types;
2. express them as a [concept](#def-b2-cpp-templates-concept) , reusing the library’s [concepts](#def-b2-cpp-templates-concept) where they fit, and constrain the parameter with it;
3. write the body using only those operations, and check that each use is covered (a use the [concept](#def-b2-cpp-templates-concept) does not cover compiles for the types tried so far and fails, inside the body, for the next one, [Exercise 4.6](#exo-b2-cpp-templates-6) );
4. test the [template](#def-b2-cpp-templates-template) with two types that satisfy the [concept](#def-b2-cpp-templates-concept) and one that does not, checking that the last is refused at the call.

## 4.5 Static against dynamic polymorphism

A [function template](#def-b2-cpp-templates-template) and a [virtual function](https://one-course.com/books/computer-science/4/en/chapter/3-inheritance-and-polymorphism#def-b2-cpp-polymorphism-virtual) both let one piece of code work with many types. They choose at different times.

**Definition 4.9 (Static polymorphism).**

*Static polymorphism* is the use of [templates](#def-b2-cpp-templates-template) to write code that works with every type satisfying its requirements, where the operation to run for each type is chosen at compile time, during instantiation. It is opposed to the [subtype polymorphism](https://one-course.com/books/computer-science/4/en/chapter/3-inheritance-and-polymorphism#def-b2-cpp-polymorphism-dispatch) of [Chapter 3](https://one-course.com/books/computer-science/4/en/chapter/3-inheritance-and-polymorphism#ch-b2-cpp-polymorphism), chosen at run time through a [dispatch table](https://one-course.com/books/computer-science/4/en/chapter/3-inheritance-and-polymorphism#def-b2-cpp-polymorphism-vtable).

[Static polymorphism](#def-b2-cpp-templates-static-poly) costs no [table pointer](https://one-course.com/books/computer-science/4/en/chapter/3-inheritance-and-polymorphism#def-b2-cpp-polymorphism-vtable) and no indirect call, and the compiler can inline the chosen operation into the caller, then optimise the result as a whole. It costs one copy of the code per type, and the set of types must be known when the program is compiled: a vector of mixed shapes read from a file needs [dynamic dispatch](https://one-course.com/books/computer-science/4/en/chapter/3-inheritance-and-polymorphism#def-b2-cpp-polymorphism-dispatch). The two sorts of the standard libraries illustrate the difference. `qsort` receives its comparison as a function pointer and calls it for every comparison; `std::sort` is a [template](#def-b2-cpp-templates-template) whose comparison type is a parameter, so that each instantiation can inline it.

```cpp
int main()
{
    std::mt19937 gen(2025);
    std::printf("%10s %10s %12s %8s\n", "n", "qsort ms", "std::sort ms", "ratio");
    for (int n = 10000; n <= 10000000; n *= 10) {
        std::vector<int> a(n);
        for (int &x : a) x = int(gen());
        std::vector<int> b = a;
        double q = ms([&] { std::qsort(a.data(), a.size(), sizeof(int), compare_ints); });
        double s = ms([&] { std::sort(b.begin(), b.end(),
            [](int x, int y) { return x < y; }); });
        if (a != b) return 1;                        // both sorted the same values
        std::printf("%10d %10.2f %12.2f %8.1f\n", n, q, s, q / s);
    }
    return 0;
}
```

***Listing 4.10.** Sorting the same random integers both ways; `compare_ints` returns the sign of $x - y$ code/bachelor-2/04-cpp-templates/listings/sort_compare.cpp*

```
$ g++ -std=c++20 -O2 -Wall -Wextra -o sort_compare sort_compare.cpp && ./sort_compare
         n   qsort ms std::sort ms    ratio
     10000       0.57         0.36      1.6
    100000       7.99         4.84      1.6
   1000000      88.11        44.70      2.0
  10000000    1006.54       566.32      1.8
```

***Output 4.9.** One run on the author’s laptop; the digits change from run to run.*

![Where the comparison happens. qsort is compiled once for every type, so it can only call the comparison through a pointer it receives; std::sort is instantiated for int and the lambda’s type, and the comparison becomes part of its own loop.](https://one-course.com/images/onecourse/chapters/computer-science-4/b2-cpp-templates/fig-3bfd8b73ca66.svg)

*Where the comparison happens. `qsort` is compiled once for every type, so it can only call the comparison through a pointer it receives; `std::sort` is instantiated for `int` and the lambda’s type, and the comparison becomes part of its own loop.*

Both sort the same values in time growing like $n \log n$, and `std::sort` is faster by a factor that the run shows to lie between 1.6 and 2, from the smallest array to the largest: the function call, the two loads through `void *` and the three-way result of `compare_ints` (computed without a branch, but tested by `qsort` after the call), repeated $n \log_2 n$ times, against a single comparison inside the loop. The C standard requires nothing of `qsort`’s speed: neither its algorithm nor its complexity is specified. `std::sort` must make $O(n \log n)$ comparisons in the worst case.

**In practice — Templates or virtual functions.**

Use a [template](#def-b2-cpp-templates-template) when the types are known at compile time and the operation is small and called often: containers, algorithms, numeric code. Use [virtual functions](https://one-course.com/books/computer-science/4/en/chapter/3-inheritance-and-polymorphism#def-b2-cpp-polymorphism-virtual) when the set of types is open, or chosen at run time from data, or when one compiled copy must serve every type: plug-ins, the library’s fine policies. Mixed designs are common: a [template](#def-b2-cpp-templates-template) container of `std::unique_ptr` to a [base class](https://one-course.com/books/computer-science/4/en/chapter/3-inheritance-and-polymorphism#def-b2-cpp-polymorphism-inheritance) holds objects of any [derived class](https://one-course.com/books/computer-science/4/en/chapter/3-inheritance-and-polymorphism#def-b2-cpp-polymorphism-inheritance).

## 4.6 Exercises

**Exercise 4.1 ★.**

For each call a to g, say which `show` runs, and with which `T` if it is a [template](#def-b2-cpp-templates-template). The rule: among the candidates that match, an exact match beats a conversion, and an ordinary function beats a [template](#def-b2-cpp-templates-template) when both match equally well.

```cpp
void show(int) { std::puts("show(int)"); }
void show(double) { std::puts("show(double)"); }
template <typename T> void show(T) { std::puts("show<T>(T)"); }
template <typename T> void show(T *) { std::puts("show<T>(T *)"); }

int main()
{
    int n = 1;
    show(1);            // a
    show(1.5);          // b
    show(1.5f);         // c
    show('x');          // d
    show<int>(1);       // e
    show(&n);           // f
    show(nullptr);      // g
    return 0;
}
```

***Listing 4.11.** Four candidates, seven calls code/bachelor-2/04-cpp-templates/listings/exo_overload.cpp*

**Solution of Exercise 4.1.**

```
$ g++ -std=c++20 -O2 -Wall -Wextra -o exo_overload exo_overload.cpp && ./exo_overload
show(int)
show(double)
show<T>(T)
show<T>(T)
show<T>(T)
show<T>(T *)
show<T>(T)
```

***Output 4.13.** The seven lines.*

a: `show(int)` is an exact match and not a [template](#def-b2-cpp-templates-template), so it wins over the [template](#def-b2-cpp-templates-template) with `T = int`. b: the same with `show(double)`. c: `1.5f` is a `float`; `show(double)` needs a promotion, the [template](#def-b2-cpp-templates-template) with `T = float` is exact. d: `'x'` is a `char`: exact for the [template](#def-b2-cpp-templates-template) with `T = char`, a promotion for `show(int)`. e: explicit [template](#def-b2-cpp-templates-template) arguments leave only [templates](#def-b2-cpp-templates-template), `T = int`. f: both [templates](#def-b2-cpp-templates-template) match exactly (`T = int *` and `T = int`); the one with parameter `T *` is more specialised and wins. g: `nullptr` has type `std::nullptr_t`, which converts to no `int` or `double` and from which `T *` cannot be deduced; only `show<T>(T)` matches.

**Exercise 4.2 ★.**

A programmer moves the body of a [function template](#def-b2-cpp-templates-template) into its own source file, as one does for ordinary functions: `twice.hpp` declares `template <typename T> T twice(T x);`, `twice.cpp` defines it, and `main_twice.cpp` calls `twice(21)`. Each file compiles; the link fails. Explain, with [Definition 4.4](#def-b2-cpp-templates-instantiation), and give two fixes.

```
/usr/bin/ld: main_twice.o: in function `main':
main_twice.cpp:(.text+0xe): undefined reference to `int twice<int>(int)'
collect2: error: ld returned 1 exit status
```

***Output 4.10.** The linker’s message. Some lines are left out.*

**Solution of Exercise 4.2.**

`main_twice.cpp` sees only the declaration, so the compiler emits a call to `twice<int>` and trusts the linker to find it. `twice.cpp` contains the [template](#def-b2-cpp-templates-template) but never uses it, so nothing there is instantiated, and no file defines `twice<int>`: the linker reports it undefined. Fix 1, the usual one: define the [template](#def-b2-cpp-templates-template) in the header. Fix 2: keep the definition in `twice.cpp` and add an *explicit instantiation*, `template int twice<int>(int);`, for every argument list the program will use, which only works when that list is known in advance.

**Exercise 4.3 ★.**

Write `clamp_to(x, lo, hi)`, which returns `lo` if $x < lo$, `hi` if $hi < x$ and `x` otherwise, for any type with a `<`, stated as a [concept](#def-b2-cpp-templates-concept); it throws if $hi < lo$. Check that a type without `<` is refused at the call, and say why the function returns a `const T &`. Is that safe when `lo` is a temporary?

**Solution of Exercise 4.3.**

```cpp
template <typename T>
concept TotallyOrdered = requires(const T a, const T b) {
    { a < b } -> std::convertible_to<bool>;
};

template <TotallyOrdered T>
const T &clamp_to(const T &x, const T &lo, const T &hi)
{
    if (hi < lo)
        throw std::invalid_argument("clamp_to: hi < lo");
    if (x < lo) return lo;
    if (hi < x) return hi;
    return x;
}
```

*`clamp_to` code/bachelor-2/04-cpp-templates/exercises/clamp.hpp*

It returns a reference to one of its arguments to avoid a copy of a large value. That is safe when the result is used at once or copied, as in `int y = clamp_to(x, 0, 10);`. It dangles in `const int &r = clamp_to(x, 0, 10);` when the result is the temporary `0` or `10`, which dies at the end of the statement: the same caveat as for the standard `std::clamp`. `tests/exercises_test.cpp` checks a type without `<` is refused, through a [concept](#def-b2-cpp-templates-concept) that asks whether the call is valid.

**Exercise 4.4 ★.**

A program uses `Vec<int>`, `Vec<double>` and `Vec<std::string>`, calls `push_back` on all three, `at` on the first only, and copies the third. Using [Proposition 4.5](#prop-b2-cpp-templates-instantiations), list the instantiated [member functions](https://one-course.com/books/computer-science/4/en/chapter/1-from-c-to-c-classes-and-resource-management#def-b2-cpp-classes-raii-class) of `Vec` (count `reserve` and `clear`, which `push_back` and the [destructor](https://one-course.com/books/computer-science/4/en/chapter/1-from-c-to-c-classes-and-resource-management#def-b2-cpp-classes-raii-constructor) call). How does the list change if the program is split into two files that both use `Vec<int>`?

**Solution of Exercise 4.4.**

For each of `int`, `double` and `std::string`: the [constructor](https://one-course.com/books/computer-science/4/en/chapter/1-from-c-to-c-classes-and-resource-management#def-b2-cpp-classes-raii-constructor) and [destructor](https://one-course.com/books/computer-science/4/en/chapter/1-from-c-to-c-classes-and-resource-management#def-b2-cpp-classes-raii-constructor), `push_back`, `reserve` and `clear`; plus `at` for `Vec<int>` and the [copy constructor](https://one-course.com/books/computer-science/4/en/chapter/2-copying-moving-and-smart-pointers#def-b2-cpp-copy-move-copy) for `Vec<std::string>`, and the `const` `operator[]` that this [copy constructor](https://one-course.com/books/computer-science/4/en/chapter/2-copying-moving-and-smart-pointers#def-b2-cpp-copy-move-copy) calls on its argument: 18 [member functions](https://one-course.com/books/computer-science/4/en/chapter/1-from-c-to-c-classes-and-resource-management#def-b2-cpp-classes-raii-class) (the defaulted [constructor](https://one-course.com/books/computer-science/4/en/chapter/1-from-c-to-c-classes-and-resource-management#def-b2-cpp-classes-raii-constructor) may generate no code). Members never used, such as `capacity`, are not instantiated. Split in two files that both use `Vec<int>`, each object file contains its own copies of the `Vec<int>` members, as weak symbols, and the linker keeps one of each: the program contains the same 18 functions.

**Exercise 4.5 ★★.**

Two of these three calls do not compile; the third compiles and is wrong. Explain the two messages with [Definition 4.2](#def-b2-cpp-templates-deduction), fix each call, and explain what the third compares.

```cpp
template <typename T> T larger(T a, T b) { return a < b ? b : a; }
template <typename T> T parse(const std::string &s) { return T(s.size()); }

int main()
{
    int a = larger(3, 7.5);                 // 1
    auto n = parse("12");                   // 2
    std::string s = larger("pier", "dunes rd");   // 3
    return a + int(n) + int(s.size());
}
```

***Listing 4.12.** Three calls code/bachelor-2/04-cpp-templates/listings/exo_deduce.cpp*

```
exo_deduce.cpp:10:19: error: no matching function for call to 'larger(int, double)'
exo_deduce.cpp:10:19: note:   deduced conflicting types for parameter 'T' ('int' and 'double')
exo_deduce.cpp:11:19: error: no matching function for call to 'parse(const char [3])'
exo_deduce.cpp:11:19: note:   couldn't deduce template parameter 'T'
```

***Output 4.11.** The key lines of the two errors. Some lines are left out.*

**Solution of Exercise 4.5.**

1: `T` is deduced as `int` from 3 and as `double` from 7.5, a conflict; write `larger<double>(3, 7.5)` or `larger(3.0, 7.5)`. 2: `T` appears only in the return type, so nothing deduces it; write `parse<int>("12")`. 3: the two arguments are arrays of 5 and 9 characters, which, passed by value, decay to pointers: `T` is `const char *` for both, and the call compiles. It compares two *addresses* of unrelated string literals, whose order is unspecified, and returns one of the two pointers, converted to a string. Fix: `larger(std::string("pier"), std::string("dunes rd"))`.

**Exercise 4.6 ★★.**

The [concept](#def-b2-cpp-templates-concept) below is satisfied by `double` and by `std::string`, and yet the call with strings does not compile. Explain the message, and say which step of [Method 4.8](#met-b2-cpp-templates-concept-first) was skipped. Write the [concept](#def-b2-cpp-templates-concept) the body really needs.

```cpp
template <typename T>
concept Ordered = requires(const T a, const T b) { { a < b } -> std::convertible_to<bool>; };

template <Ordered T>
T middle(const std::vector<T> &v)           // the mean of the smallest and the largest
{
    T lo = v[0], hi = v[0];
    for (const T &x : v) {
        if (x < lo) lo = x;
        if (hi < x) hi = x;
    }
    return (lo + hi) / 2;
}

int main()
{
    std::vector<double> d = {3.5, 1.0, 8.0};
    std::vector<std::string> s = {"pier", "dunes"};
    double m = middle(d);
    std::string t = middle(s);
    return int(m) + int(t.size());
}
```

***Listing 4.13.** A middle value code/bachelor-2/04-cpp-templates/listings/exo_weak_concept.cpp*

```
exo_weak_concept.cpp: In instantiation of 'T middle(const std::vector<T>&) [with T = std::__cxx11::basic_string<char>]':
exo_weak_concept.cpp:26:27:   required from here
exo_weak_concept.cpp:18:22: error: no match for 'operator/' (operand types are 'std::__cxx11::basic_string<char>' and 'int')
   18 |     return (lo + hi) / 2;
      |            ~~~~~~~~~~^~~
```

***Output 4.12.** The error, inside the body. Some lines are left out.*

**Solution of Exercise 4.6.**

`Ordered` asks only for `<`, and both types have it, so the call is accepted; the body also computes `(lo + hi) / 2`, and for strings `+` concatenates but nothing divides a string by 2. Steps 1 and 3 of [Method 4.8](#met-b2-cpp-templates-concept-first) were skipped: the operations of the body were not all listed. The right [concept](#def-b2-cpp-templates-concept) also requires `{(a + b) / 2} -> std::convertible_to<T>` in its `requires` expression; strings are then refused at the call.

**Exercise 4.7 ★★.**

Write a [function template](#def-b2-cpp-templates-template) `lower_bound_of(first, last, key)` that returns the first position $p$ of a sorted range with `!(*p < key)`, or `last`, for any random-access iterator (a [concept](#def-b2-cpp-templates-concept) of the library) and any key comparable with the elements. State its loop invariant. Test it against `std::lower_bound` on random sorted vectors and every key in a range.

**Solution of Exercise 4.7.**

```cpp
template <std::random_access_iterator It, typename K>
    requires requires(It p, const K &k) { { *p < k } -> std::convertible_to<bool>; }
It lower_bound_of(It first, It last, const K &key)
{
    auto n = last - first;                  // invariant: the answer lies in [first, first + n]
    while (n > 0) {
        auto half = n / 2;
        It mid = first + half;
        if (*mid < key) {
            first = mid + 1;
            n -= half + 1;
        } else {
            n = half;
        }
    }
    return first;
}

template <std::random_access_iterator It, typename K>
bool contains(It first, It last, const K &key)
{
    It p = lower_bound_of(first, last, key);
    return p != last && !(key < *p);
}
```

*Binary search over any random-access range code/bachelor-2/04-cpp-templates/exercises/bsearch.hpp*

Invariant: every element before `first` is less than the key, and every element from `first + n` on is not; the answer is therefore in $[\texttt{first}, \texttt{first} + n]$. Each step keeps it and at least halves $n$, so the loop ends after at most $\lceil \log_2(n + 1) \rceil$ steps with $n = 0$, and `first` is the answer. The test compares with `std::lower_bound` and `std::binary_search` on 200 random sorted vectors and every key from $-1$ to 41.

**Exercise 4.8 ★★.**

A [class template](#def-b2-cpp-templates-template) `Pow<N>`, with a [template parameter](#def-b2-cpp-templates-template) `unsigned N`, has one member, the constant `static constexpr long value = 3 * Pow<N - 1>::value;`, and a [full specialisation](#def-b2-cpp-templates-specialisation) `Pow<0>` whose `value` is 1: `Pow<N>::value` is $3^N$, computed at compile time. How many classes does `Pow<20>::value` instantiate? And a program that uses `Pow<20>` and `Pow<25>`? Write the same with a `constexpr` function and compare what the compiler must generate.

**Solution of Exercise 4.8.**

`Pow<20>::value` needs `Pow<19>::value`, which needs `Pow<18>`, and so on down to `Pow<0>`, the specialisation written by hand: 20 classes instantiated, `Pow<1>` to `Pow<20>`. With `Pow<25>` as well, only `Pow<21>` to `Pow<25>` are new, since each class is instantiated once ([Proposition 4.5](#prop-b2-cpp-templates-instantiations)): 25 in all. A `constexpr` function `power(3, n)` is one function, which the compiler runs on the constant arguments; no class at all is generated, and compile-time loops are no longer limited by the depth of recursive instantiation.

**Exercise 4.9 ★★.**

Write `Matrix<T, R, C>`, stored in a `std::array<T, R * C>`, with element access, `transpose` and a product `operator*` that accepts only matrices of matching inner dimension, so that multiplying a $2 \times 3$ by a $2 \times 3$ matrix does not compile. Check that refusal with a `static_assert` and a [concept](#def-b2-cpp-templates-concept).

**Solution of Exercise 4.9.**

```cpp
template <typename T, std::size_t R, std::size_t C>
struct Matrix {
    std::array<T, R * C> a{};               // row by row
    T &operator()(std::size_t i, std::size_t j) { return a[i * C + j]; }
    const T &operator()(std::size_t i, std::size_t j) const { return a[i * C + j]; }
};

// (R x K) times (K x C): the shared K is checked by the compiler, not at run time.
template <typename T, std::size_t R, std::size_t K, std::size_t C>
Matrix<T, R, C> operator*(const Matrix<T, R, K> &x, const Matrix<T, K, C> &y)
{
    Matrix<T, R, C> z;
    for (std::size_t i = 0; i < R; i++)
        for (std::size_t j = 0; j < C; j++)
            for (std::size_t k = 0; k < K; k++)
                z(i, j) += x(i, k) * y(k, j);
    return z;
}

template <typename T, std::size_t R, std::size_t C>
Matrix<T, C, R> transpose(const Matrix<T, R, C> &x)
{
    Matrix<T, C, R> t;
    for (std::size_t i = 0; i < R; i++)
        for (std::size_t j = 0; j < C; j++)
            t(j, i) = x(i, j);
    return t;
}
```

*Dimensions in the type code/bachelor-2/04-cpp-templates/exercises/matrix.hpp*

The product is a [template](#def-b2-cpp-templates-template) in four parameters, `T`, `R`, `K` and `C`, and its two parameters share `K`: a $2 \times 3$ by a $2 \times 3$ would need $K = 3$ and $K = 2$ at once, deduction fails, and there is no other `operator*`. The test defines the [concept](#def-b2-cpp-templates-concept) `Multipliable<A, B>` (the product is valid) and asserts it for $2 \times 3$ by $3 \times 4$ and refutes it for $2 \times 3$ by $2 \times 3$, at compile time; it also checks $M M^{\mathsf{T}}$ for a $2 \times 3$ matrix.

**Exercise 4.10 ★★★.**

Write a binary heap `Heap<T, Less = std::less<T>>` over a `std::vector<T>`, with `push`, `top` and `pop`, the comparator being a [template parameter](#def-b2-cpp-templates-template) stored in the object. Test it against a sorted copy for 500 random values, and as a min-heap of strings with `std::greater`. Why can the comparator be inlined here and not in `qsort`?

**Solution of Exercise 4.10.**

```cpp
template <typename T, typename Less = std::less<T>>
class Heap {
public:
    explicit Heap(Less less = Less()) : less_(less) {}
    void push(T x)
    {
        v_.push_back(std::move(x));
        std::size_t i = v_.size() - 1;
        while (i > 0 && less_(v_[(i - 1) / 2], v_[i])) {     // sift up
            std::swap(v_[(i - 1) / 2], v_[i]);
            i = (i - 1) / 2;
        }
    }
    const T &top() const
    {
        if (v_.empty()) throw std::out_of_range("Heap::top on an empty heap");
        return v_[0];
    }
    void pop()
    {
        if (v_.empty()) throw std::out_of_range("Heap::pop on an empty heap");
        v_[0] = std::move(v_.back());
        v_.pop_back();
        std::size_t i = 0, n = v_.size();
        for (;;) {                                              // sift down
            std::size_t l = 2 * i + 1, r = l + 1, m = i;
            if (l < n && less_(v_[m], v_[l])) m = l;
            if (r < n && less_(v_[m], v_[r])) m = r;
            if (m == i) break;
            std::swap(v_[i], v_[m]);
            i = m;
        }
    }
    std::size_t size() const { return v_.size(); }
    bool empty() const { return v_.empty(); }

private:
    std::vector<T> v_;
    Less less_;
};
```

*`Heap<T, Less>` code/bachelor-2/04-cpp-templates/exercises/heap.hpp*

`push` adds at the end and sifts up while the parent is “less”; `pop` moves the last element to the root and sifts it down, choosing the larger child. Each instantiation knows the comparator’s *type*, hence the exact function it calls (for `std::less<int>`, the built-in `<`), and can inline it. `qsort` receives a pointer *value*, known only when the program runs, and is compiled once in the C library: it must make an indirect call each time.

**Exercise 4.11 ★★★.**

A library [template](#def-b2-cpp-templates-template) has $m$ [member functions](https://one-course.com/books/computer-science/4/en/chapter/1-from-c-to-c-classes-and-resource-management#def-b2-cpp-classes-raii-class) of about $b$ bytes of machine code each, and a program uses it with $k$ types, every member with every type. (a) Bound the code size the [template](#def-b2-cpp-templates-template) contributes, with [Proposition 4.5](#prop-b2-cpp-templates-instantiations). (b) The program is built from $u$ files that each use all $k$ types: what do the object files contain before linking, and the program after? (c) From [Output 4.4](#out-b2-cpp-templates-instantiate), how many functions of `Vec` does `vec_demo.o` contain per type, roughly? Compare with a `void *` version, compiled once.

**Solution of Exercise 4.11.**

(a) At most $kmb$ bytes: one copy of each member per type. (b) Each of the $u$ object files contains up to $km$ functions, $ukm$ weak copies in all; the program, after linking, $km$. The compile time grows with $u$, the program does not. (c) 30 symbols for 3 types, about 10 functions per type ([constructors](https://one-course.com/books/computer-science/4/en/chapter/1-from-c-to-c-classes-and-resource-management#def-b2-cpp-classes-raii-constructor), [destructor](https://one-course.com/books/computer-science/4/en/chapter/1-from-c-to-c-classes-and-resource-management#def-b2-cpp-classes-raii-constructor), `push_back`, `reserve`, `clear`, `operator[]`, `begin`, `end` and others). A `void *` version is compiled once, about 10 functions for every type together, at the price of the type checks and the inlining.

**Exercise 4.12 ★★★.**

Write `pascal<N>()`, a `constexpr` function returning the table of binomial coefficients $\binom{n}{k}$ for $0 \leq k \leq n \leq N$ as nested `std::array`s, computed by Pascal’s rule. Keep it in a `constexpr` variable for $N = 67$, and check with `static_assert` that $\binom{5}{2} = 10$ and that $\binom{67}{33}$ fits in 64 bits. Why is 67 the largest $N$ for which every entry fits in an unsigned 64-bit integer? Test Pascal’s rule and the row sums $2^n$ at run time.

**Solution of Exercise 4.12.**

```cpp
template <std::size_t N>
constexpr std::array<std::array<std::uint64_t, N + 1>, N + 1> pascal()
{
    std::array<std::array<std::uint64_t, N + 1>, N + 1> c{};
    for (std::size_t n = 0; n <= N; n++) {
        c[n][0] = 1;
        for (std::size_t k = 1; k <= n; k++)
            c[n][k] = c[n - 1][k - 1] + c[n - 1][k];    // c[n-1][n] is 0
    }
    return c;
}

inline constexpr auto BINOM = pascal<67>();           // the last full row that fits in 64 bits

static_assert(BINOM[5][2] == 10);
static_assert(BINOM[67][33] == 14226520737620288370ULL);
```

*Pascal’s triangle at compile time code/bachelor-2/04-cpp-templates/exercises/binomial.hpp*

The largest entry of row $n$ is the middle one. $\binom{67}{33} \approx 1.42 \times 10^{19}$ is below $2^{64} \approx
1.84 \times 10^{19}$, and $\binom{68}{34} \approx 2.85 \times 10^{19}$ is above: 67 is the last row that fits entirely. Pascal’s rule only adds entries of the previous row, and each sum is an entry of the table, so no intermediate result overflows up to $N = 67$. The test checks the rule for every entry and the row sum $\sum_k \binom{20}{k} = 2^{20}$.

## 4.7 Problem: One sort for every type

**Problem 4.1.**

Weekend problem — One sort for every type

The town keeps tables of readings (`double`), of people sorted by name (`std::string`) and of loans sorted by date (a `struct`). This problem sorts all three with one generic function and measures what it gains over `qsort`.

**Part I — `qsort` and `void *`.**

1. Write the comparison function `qsort` needs for `double` s. Why is `return x - y;` wrong for `double` , and for `int` near the ends of its range?
2. Write the comparison for an array of `struct loan {int id; int due;}` by due date, then by `id` .
3. Why can `qsort` not sort an array of `std::string` correctly? (It moves elements byte by byte.)
4. What does the compiler check about the arguments of a `qsort` call? Give a call that compiles and sorts garbage.
5. `compare_ints` in [Listing 4.10](#lst-b2-cpp-templates-sort-compare) is called how many times, roughly, for $n = 10^6$ ? Use $n \log_2 n$ .
6. What does the C standard promise about `qsort` ’s running time and stability?

**Part II — A template sort.**

7. Write `template <typename T, typename Less> void insertion_sort(T *a, std::size_t n, Less less)` .
8. Call it on `double` s with a lambda, on `std::string` s with `std::less<>` , and on loans with a lambda comparing due dates then ids.
9. Which functions does the compiler instantiate for these three calls?
10. Why are the strings now moved correctly, where `qsort` copied bytes?
11. Rewrite the swap of two elements so that it moves, and say what it costs for strings longer than the small buffer of [Chapter 2](https://one-course.com/books/computer-science/4/en/chapter/2-copying-moving-and-smart-pointers#ch-b2-cpp-copy-move) .
12. Insertion sort makes up to $n(n-1)/2$ comparisons. Why would a [template](#def-b2-cpp-templates-template) version still lose to `qsort` for $n = 10^6$ ?

**Part III — Concepts.**

13. State, as a [concept](#def-b2-cpp-templates-concept) , what `insertion_sort` requires of `Less` given `T` .
14. Which [concept](#def-b2-cpp-templates-concept) of the library expresses “ `T` can be moved and move-assigned”? Add it.
15. A caller passes a comparator that takes its arguments by non-const reference. Does it satisfy your [concept](#def-b2-cpp-templates-concept) ? Should it?
16. A comparator `[](double x, double y) {return x <= y;}` satisfies the [concept](#def-b2-cpp-templates-concept) . Why is it still wrong for a sort? Can a [concept](#def-b2-cpp-templates-concept) detect it?
17. Rewrite the sort to take a pair of random-access iterators instead of a pointer and a size. Which library [concept](#def-b2-cpp-templates-concept) do you use?
18. Write a test that checks, for each of the three types, that the result is sorted and is a permutation of the input.

**Part IV — The measured speed-up.**

19. From [Output 4.9](#out-b2-cpp-templates-sort-compare) , compute the time per element and per comparison of each sort for $n = 10^6$ .
20. Is the ratio roughly constant over $n$ ? What does that say about where the difference comes from?
21. Explain, with the figure on the two sorts, what the processor does per comparison in each case.
22. The town sorts a million readings once a night. Is the difference worth a rewrite? And a trading system that sorts ten thousand orders every millisecond?
23. The `sort_compare` program was compiled with `-O2` . Predict the ratio at `-O0` , where nothing is inlined.
24. State the result of the problem: the speed-up of `std::sort` over `qsort` measured on the laptop, and its cause.

**Solution of Problem 4.1.**

**1.** Read both values as `double` and return `(x > y) - (x < y)`. `x - y` is converted to `int`: a difference of 0.5 becomes 0, “equal”. For `int`, `x - y` overflows when, say, $x$ is near `INT_MAX` and $y$ negative, which is undefined behaviour and in practice gives the wrong sign.

**2.** Compare `due` with the same three-way formula, and if equal, compare `id`.

**3.** `qsort` swaps elements as blocks of bytes. A `std::string` may point into its own small buffer or own a heap block; a byte copy breaks the first (the pointer still points into the old place) and duplicates the owner of the second. Moving C++ objects that are not trivially copyable without their [constructors](https://one-course.com/books/computer-science/4/en/chapter/1-from-c-to-c-classes-and-resource-management#def-b2-cpp-classes-raii-constructor) is undefined behaviour.

**4.** Only the types of the four arguments: any object pointer converts to `void *`. `qsort(d, n, sizeof(int), compare_ints)` on an array of `double` compiles and sorts garbage.

**5.** About $n \log_2 n = 10^6 \times 20 = 2 \times 10^7$ calls.

**6.** Nothing: no algorithm, no complexity, no stability.

**7.** For $i$ from 1 to $n - 1$: `T x = std::move(a[i])`; shift the elements before it that are greater than `x` (`less(x, a[j - 1])`) one place right, by move-assignment; put `x` in the hole.

**8.** A lambda `(double x, double y) -> x < y`; `std::less<>()`; a lambda that compares `due`, then `id`.

**9.** Three functions: `insertion_sort` for `double` with the first lambda’s type, for `std::string` with `std::less<void>`, and for `loan` with the second lambda’s type (every lambda has a type of its own).

**10.** The [template](#def-b2-cpp-templates-template) is compiled for `std::string` and moves elements with `std::string`’s [move constructor](https://one-course.com/books/computer-science/4/en/chapter/2-copying-moving-and-smart-pointers#def-b2-cpp-copy-move-move) and assignment, which keep its invariant.

**11.** `T tmp = std::move(a); a = std::move(b); b = std::move(tmp);`, or `std::swap(a, b)`: three moves of a few pointers each for long strings, whatever their length.

**12.** Up to $n^2 / 2 = 5 \times 10^{11}$ comparisons against about $2 \times 10^7$ for `qsort`: the algorithm matters far more than inlining.

**13.** A `requires` expression with parameters `L less`, `const T &a` and `const T &b`, requiring `less(a, b)` to be valid and convertible to `bool`; the library’s `std::predicate<L, const T &, const T &>` says the same.

**14.** `std::movable<T>`.

**15.** No: the [concept](#def-b2-cpp-templates-concept) calls it with `const T &`, which does not bind to `T &`. That is right: a comparison must not modify its arguments, and the sort relies on it.

**16.** `<=` is not a strict order: `x <= x` is true. Sorts assume irreflexivity; insertion sort then loses stability, and `std::sort` given such a comparator may read past the end of the range. A [concept](#def-b2-cpp-templates-concept) checks syntax, not meaning: `std::strict_weak_order` only documents the requirement.

**17.** Take two iterators `first` and `last` of a type `It` constrained by the library’s [concept](#def-b2-cpp-templates-concept) of random-access iterators, and keep `Less less`; `std::sortable<It, Less>` states both requirements at once.

**18.** For each type, sort a copy of random input and check `std::is_sorted` with the same comparator and `std::is_permutation` against the input.

**19.** In the printed run, for $n = 10^6$: `qsort` takes of the order of 90 ns per element, about 4 ns per comparison (dividing by $2 \times 10^7$); `std::sort` about half of each.

**20.** Yes, between about 1.5 and 2: the difference is a cost per comparison, not a different growth. Both make $O(n \log n)$ comparisons; each comparison costs more in `qsort`.

**21.** `qsort`: pass two addresses, make an indirect call, load the two `int`s through the pointers, compute the three-way result with two comparisons, return, and test that result. `std::sort`: one comparison of two registers, and a branch.

**22.** The night: tens of milliseconds saved, irrelevant. Ten thousand orders every millisecond: from the printed run a sort of $10^4$ elements takes about half a millisecond with `qsort`; the difference is a large share of the budget, and the rewrite is worth it.

**23.** At `-O0` nothing is inlined: `std::sort`’s comparisons become calls of the lambda’s `operator()`, and its iterator operations calls too. The ratio falls to about 1 or below.

**24.** *The comparator speed-up of `std::sort` over `qsort`, measured on the laptop*: in the printed run, a factor of about 1.5 to 2 for $10^4$ to $10^7$ integers, constant in $n$, because the comparison is inlined into the instantiated sort instead of being called through a pointer.
