Skip to content
LumenaryAcademy
Practice 65 min

Templates and concepts

Writing code once for every type that fits, and saying precisely which types fit.

Code tested · 3AI-draftedAwaiting review by a computer scientist
MotivationH

One algorithm, many types

Finding the largest element of a list is the same algorithm whether the elements are integers, prices or names. In C you would write it three times, or write it once over void* and lose all type checking. Python writes it once and checks types while the program runs. C++'s answer is the template: you write the algorithm once with a placeholder for the type, and the compiler writes a separate, fully type-checked, fully optimised version for each type you actually use.

Templates are how the whole standard library is built. std::vector, std::map, std::sort, std::unique_ptr, std::println itself: all templates. They are also the reason C++ code can be both abstract and fast, because a template instantiated for int compiles to code specialised for int, with no indirection.

For thirty years templates had a weakness: nothing said which types a template accepted. Pass the wrong type and the error appeared deep inside the library, in code you never wrote. C++20 added concepts, named requirements on types, so that a template can state its contract the way a function states its parameter types.

History & global context

Thirty years to say what a template needs

Stroustrup described templates in 1988, and they shipped in compilers in the early 1990s, originally to make type-safe containers possible. Then Alexander Stepanov, who had been working for years on generic programming (algorithms written once, for any data structure that offers the right operations), showed that templates could do far more. His Standard Template Library, built with Meng Lee, was accepted into the draft standard in 1994, and its containers, iterators and algorithms became the heart of C++98.

Stepanov's algorithms always had requirements on their types: "the iterators must allow random access", "the elements must be comparable". But those requirements lived only in documentation. A proposal to put them in the language was part of the C++11 draft until 2009, when the committee removed it as too complex and too late. A simplified design was published as a Technical Specification in 2015, refined, and finally adopted as concepts in C++20, together with the ranges library rebuilt on top of them. The story is a good example of how C++ evolves: slowly, by consensus, with features tried outside the standard before they are frozen into it.

DefinitionsH

Definitions

Definition— function template and class template

A function or class with template parameters, written template <typename T> before it. T stands for a type to be supplied later. Template parameters can also be values, such as the std::size_t Capacity of the stack below.

Definition— instantiation and deduction

Using a template with particular arguments makes the compiler generate (instantiate) a real function or class for them. For function templates the compiler usually deduces the arguments from the call: largest(std::vector<int>{...}) deduces T = int. Since C++17, class templates can deduce theirs from a constructor call too (class template argument deduction, CTAD), and since C++20 from the initialiser of an aggregate: Pair p{"Nairobi", 1899};.

Definition— concept

A named, compile-time predicate on types, such as std::integral (is it an integer type?) or std::totally_ordered (do <, >, == work as an ordering?). A concept is used to constrain a template: the template is only considered for arguments that satisfy it.

Definition— requires-expression

The building block of custom concepts: requires(const S& s) { s.area(); } is true if the expressions inside would compile for type S. A compound requirement such as { s.area() } -> std::convertible_to<double>; also checks the result type.

Definition— variadic template and fold expression

A template taking any number of arguments, template <typename... Ts>. A fold expression such as (xs + ... + 0) applies an operator across all of them.

ComputationC

Function templates and class templates

cpp
#include <print>
#include <stdexcept>
#include <string>
#include <vector>

// A function template: one definition, any element type with <.
template <typename T>
T largest(const std::vector<T>& items) {
    if (items.empty()) throw std::invalid_argument("largest of nothing");
    T best = items.front();
    for (const T& x : items) {
        if (best < x) best = x;
    }
    return best;
}

// A class template: a fixed-capacity stack whose element type and size are parameters.
template <typename T, std::size_t Capacity>
class SmallStack {
public:
    bool push(const T& value) {
        if (size_ == Capacity) return false;
        items_[size_++] = value;
        return true;
    }
    T pop() { return items_[--size_]; }
    bool empty() const { return size_ == 0; }
    std::size_t size() const { return size_; }

private:
    T items_[Capacity]{};
    std::size_t size_ = 0;
};

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

int main() {
    std::println("{}", largest(std::vector<int>{3, 41, 7}));           // T = int
    std::println("{}", largest(std::vector<double>{2.5, -1.0}));       // T = double
    std::println("{}", largest(std::vector<std::string>{"kiwi", "mango", "fig"}));

    SmallStack<char, 3> s;
    for (char c : std::string("abcd")) {
        if (!s.push(c)) std::println("full, dropped '{}'", c);
    }
    while (!s.empty()) std::print("{}", s.pop());
    std::println("");

    Pair p{"Nairobi", 1899};   // class template argument deduction: Pair<const char*, int>
    std::println("{} founded {}", p.first, p.second);
}
text
41
2.5
mango
full, dropped 'd'
cba
Nairobi founded 1899

largest was instantiated three times, for int, double and std::string; each version is an ordinary function with the type filled in. The template places implicit requirements on T: it must be copyable and comparable with <. A vector of a type without < would fail to compile, inside largest, at the line if (best < x). That is the problem concepts solve.

SmallStack takes a type and a number. SmallStack<char, 3> and SmallStack<char, 4> are different types, and the array inside each has its size fixed at compile time, so the stack needs no heap allocation at all. (The standard library's std::array is this idea, done properly.)

Note

Inside a template, the compiler cannot know what a name that depends on T refers to until T is known. If you write T::value_type x; it assumes value_type is a value, not a type, and complains. Write typename T::value_type x; to say it is a type. You will meet this "dependent name" rule the first time you write a template over containers; modern code often sidesteps it with alias templates such as std::ranges::range_value_t (used in the example below) or with auto, and C++20 made typename optional in some places where only a type could appear.

Template definitions must be visible wherever they are instantiated, because the compiler needs the body to generate code for a new type. That is why templates live in headers, entirely, and why big template libraries can slow compilation: every file that includes them may instantiate them again. Modules and explicit instantiation help; mostly, people live with it.

Worked examplesH

Saying what a template needs: concepts

cpp
#include <concepts>
#include <print>
#include <string>
#include <vector>

// A standard concept as a constraint: only integer types are accepted.
template <std::integral T>
T gcd(T a, T b) {
    while (b != 0) {
        T r = a % b;
        a = b;
        b = r;
    }
    return a;
}

// Our own concept: anything with an area() returning something convertible to double.
template <typename S>
concept HasArea = requires(const S& s) {
    { s.area() } -> std::convertible_to<double>;
};

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

// Abbreviated syntax: "HasArea auto" means "any type satisfying HasArea".
double total_area(const std::vector<Square>& squares, const HasArea auto& extra) {
    double sum = extra.area();
    for (const auto& s : squares) sum += s.area();
    return sum;
}

// Overloads chosen by concept: the more constrained one wins.
void describe(std::integral auto x) { std::println("{} is an integer", x); }
void describe(std::floating_point auto x) { std::println("{} is floating point", x); }
void describe(const auto& x) requires std::convertible_to<decltype(x), std::string> {
    std::println("\"{}\" is text", std::string(x));
}

int main() {
    std::println("gcd {}", gcd(84, 36));
    std::println("gcd {}", gcd(1071LL, 462LL));
    // gcd(2.5, 1.0);   // error: constraints not satisfied (double is not integral)

    std::println("total {:.2f}", total_area({{1.0}, {2.0}}, Disc{1.0}));
    static_assert(HasArea<Square>);
    static_assert(!HasArea<int>);

    describe(42);
    describe(0.5);
    describe("habari");
}
text
gcd 12
gcd 21
total 8.14
42 is an integer
0.5 is floating point
"habari" is text

There are three ways to write a constraint, and you will see all of them:

  • In place of typename: template <std::integral T>.
  • With the abbreviated syntax (C++20): const HasArea auto& extra declares a parameter of any type satisfying HasArea, without writing template at all. void f(auto x) is a template too, with no constraint.
  • With a requires clause after the parameter list, for conditions that are awkward to put elsewhere, as in the third describe.

HasArea is a custom concept: a type satisfies it if s.area() compiles for a const S& and returns something convertible to double. Square and Disc share no base class, yet both work with total_area. This is structural typing checked at compile time. The static_assert lines test the concept itself, which is a good habit when you write one.

The three describe overloads show concepts taking part in overload resolution: an int satisfies only std::integral, a double only std::floating_point, and a string literal only the third. When two constrained overloads both match, the compiler prefers the one whose constraints imply the other's (it is "more constrained"), which lets you write a general version and specialised ones side by side.

What the error looks like

Uncomment gcd(2.5, 1.0) and GCC 14 reports, at the call site:

text
main.cpp:14:32: error: no matching function for call to 'gcd(double, double)'
main.cpp:4:3: note: candidate: 'template<class T>  requires  integral<T> T gcd(T, T)'
main.cpp:4:3: note:   template argument deduction/substitution failed:
main.cpp:4:3: note: constraints not satisfied
...
/usr/local/include/c++/14.4.0/concepts:107:24: note: the expression 'is_integral_v<_Tp> [with _Tp = double]' evaluated to 'false'

The same template written with plain typename T fails inside the function body instead: error: invalid operands of types 'double' and 'double' to binary 'operator%'. For a five-line function that is just as clear. For a library function that calls helpers that call helpers, the unconstrained error appears in a file you have never opened, while the constrained one names the requirement you broke at the line you wrote. That, more than shorter messages, is what concepts buy: the template's contract is part of its declaration, checked at the boundary.

Example— Growing largest into a professional generic function

The largest at the start of the lesson accepted only a std::vector. Library-quality code accepts any range whose elements can be ordered, says so in the signature, and avoids copying elements while it searches:

cpp
template <std::ranges::forward_range R>
    requires std::totally_ordered<std::ranges::range_value_t<R>>
std::ranges::range_value_t<R> largest(R&& items) {
    auto it = std::ranges::max_element(items);
    if (it == std::ranges::end(items)) throw std::invalid_argument("largest of nothing");
    return *it;
}

Now largest works for a vector, a std::list, a std::array, a std::set or a view such as std::views::iota(1, 10). The requires clause states the real requirement on the elements, and the body delegates the loop to a standard algorithm, which is the subject of the next lesson. Reading signatures like this one fluently is a large part of reading modern library documentation.

Concepts check syntax, not meaning. std::totally_ordered checks that the comparison operators exist; it cannot check that they really describe an order. The standard concepts come with semantic requirements in their documentation, and a type that compiles but breaks them gives wrong results, not errors.

Worked examplesH

Variadic templates, if constexpr and std::formatter

cpp
#include <format>
#include <print>
#include <string>
#include <type_traits>

// A variadic template with a fold expression: any number of arguments.
template <typename... Ts>
auto sum(const Ts&... xs) {
    return (xs + ... + 0);   // expands to x1 + (x2 + (... + 0))
}

template <typename... Ts>
void print_all(const Ts&... xs) {
    ((std::print("[{}]", xs)), ...);   // one print per argument, left to right
    std::println("");
}

// if constexpr: the branch not taken is discarded at compile time.
template <typename T>
std::string kind(const T& value) {
    if constexpr (std::is_integral_v<T>) {
        return "integer, " + std::string(value % 2 == 0 ? "even" : "odd");
    } else if constexpr (std::is_floating_point_v<T>) {
        return "floating point";
    } else {
        return "something else";
    }
}

struct Point {
    int x;
    int y;
};

// Teaching std::println about our own type: a specialisation of std::formatter.
template <>
struct std::formatter<Point> {
    constexpr auto parse(std::format_parse_context& ctx) { return ctx.begin(); }
    auto format(const Point& p, std::format_context& ctx) const {
        return std::format_to(ctx.out(), "({}, {})", p.x, p.y);
    }
};

int main() {
    std::println("{} {} {}", sum(1, 2, 3), sum(1.5, 2), sum());
    print_all("Quito", 2850, 'm', 9.5);
    std::println("{} | {} | {}", kind(7), kind(2.0), kind("text"));
    Point p{3, -4};
    std::println("point {} and a padded number {:>5}", p, 42);
}
text
6 3.5 0
[Quito][2850][m][9.5]
integer, odd | floating point | something else
point (3, -4) and a padded number    42

sum accepts any number of arguments of any types that can be added; the fold (xs + ... + 0) expands at compile time into a chain of additions, and the + 0 makes sum() with no arguments legal. print_all folds over the comma operator to make one call per argument, in order. These are the tools behind std::println itself, which takes any number of arguments of any formattable types and checks the format string against them during compilation.

if constexpr chooses a branch at compile time. In kind("text"), the expression value % 2 would not compile for a string, but it is in a discarded branch, so it is never instantiated. Before C++17 the same effect needed overloads or specialisations.

Finally, the std::formatter specialisation shows how library templates are customised: you supply a version of the template for your type, and every std::format, std::print and std::println in the program can now print a Point. This one ignores format specifications (its parse accepts only {}); a fuller one would parse options such as a precision.

ExplanationH

Templates or virtual functions?

The last lesson used virtual functions: a vector of pointers to Shape, with the right area() chosen at run time. This lesson's HasArea did a similar job at compile time. Both are polymorphism, and choosing between them is a daily design decision.

Templates and conceptsVirtual functions
Decidedat compile timeat run time
Types mustsatisfy the concept (no common base needed)inherit from the base class
One container holding different typesno (each instantiation is a different type)yes, through pointers
Call costnone: calls can be inlinedan indirect call, usually not inlined
Code size and build timegrow with each instantiationone copy of the code
Code compiled before a new type existed can use itno: the template must be instantiated for the new typeyes, through the base class

Use templates when the set of types is known where the code is compiled and speed matters (containers, algorithms, numeric code). Use virtual functions when objects of different types must live together in one collection, or when new types are added by plug-ins and libraries you do not compile. Large codebases use both, often together: a template inside, a stable virtual interface at the boundary.

Common misconceptionsH

Common misconceptions

Misconception

"typename and class mean different things in a template parameter list." In template <typename T> and template <class T>, they are identical; T may be any type, including int. Modern code tends to write typename, or a concept.

Misconception

"Templates make programs slow." Templates make compilation slower and can make binaries larger. The generated code is usually as fast as hand-written code for each type, often faster than the alternatives (void* or virtual calls), because the compiler can inline and specialise it.

Misconception

"A concept proves my template is correct for all types that satisfy it." The compiler does not check a template's body against its concept. A template constrained by std::integral could still use an operation std::integral does not promise; the error would appear only when some type lacks it. Concepts are a contract for callers, and tests are still needed for the template.

Misconception

"Explicit specialisations of function templates are the way to customise behaviour for one type." For functions, a plain overload is usually simpler and behaves more predictably; specialisations do not take part in overload resolution, which surprises people (see the stretch exercise). Specialise class templates such as std::formatter and std::hash, which is what the library expects.

Exercises

Exercises

1. Templates and concepts

CoreComputational

What does this program print?

#include <print>

template <typename... Ts>
auto right_fold(Ts... xs) { return (xs - ...); }

template <typename... Ts>
auto left_fold(Ts... xs) { return (... - xs); }

int main() {
    std::println("{} {}", right_fold(10, 4, 3), left_fold(10, 4, 3));
}

2. Templates and concepts

StretchComputational

What does this program print?

#include <print>

template <typename T>
void show(T) { std::print("generic "); }

template <>
void show<int>(int) { std::print("int "); }

void show(double) { std::print("plain-double "); }

int main() {
    show(1);
    show(1.0);
    show('c');
    show(2.0f);
    std::println("");
}

3. Templates and concepts

CoreComputational

What does this program print?

#include <concepts>
#include <print>
#include <string>

template <typename T>
concept Measurable = requires(const T& t) {
    { t.size() } -> std::convertible_to<std::size_t>;
};

int main() {
    std::println("{} {} {}", Measurable<std::string>, Measurable<int>, Measurable<const char*>);
}

4. Templates and concepts

Warm-upHuman

Given template <typename A, typename B> struct Pair { A first; B second; };, what type does Pair p{"Nairobi", 1899}; give p?

Choose one

5. Templates and concepts

CoreHuman

A team declares template <typename T> T clamp_to_range(T x, T lo, T hi); in util.hpp and defines it in util.cpp. Code in main.cpp calls clamp_to_range(5, 0, 3). What happens?

Choose one

6. Templates and concepts

CoreHuman

In which of these situations are virtual functions (run-time polymorphism) a better fit than templates? Select all that apply.

Choose all that apply

Further reading and resources