Module 8 · Lesson 23 of 90

Concepts and requires clauses

Constrain templates with C++20 concepts, requires clauses and constrained auto, write all four requirement kinds, and enforce API contracts at compile time.

  • Beginner to advanced
  • 12 min read
  • 30 min lab
What you will need

Ubuntu 24.04 in WSL2 or a VM with g++ (GCC 13) and -std=c++20 support; no board needed

Your place in the module
By the end you can 4 objectives
  • Define a concept and use it to constrain a template in all three syntactic positions
  • Write requires expressions using simple, type, compound and nested requirements
  • Declare abbreviated function templates with constrained auto parameters
  • Explain why a more constrained overload wins through subsumption and constraint normalization
Video coming soonConcepts and requires clauses
The video for this lesson is being recorded. Read the lesson below in the meantime.
Recall first from Compile-time branching and computation
  • Inside a template, the discarded branch of if constexpr is not instantiated; outside templates both branches must still be valid code.
  • static_assert turns a false constant expression into a compile error carrying your message, with zero run-time cost.
  • std::integral_constant and std::bool_constant carry values as types; ::value converts back, and variable templates like is_integral_v are the shorthand.
01

Concepts: stating a template's contract

5 min read

The previous lesson computed and checked values at compile time. This lesson replaces SFINAE constraints with C++20 concepts and requires clauses that state a template's contract directly, including abbreviated function templates.

Start from the problem concepts solve. An unconstrained function template accepts every type, and the compiler only discovers a mismatch when it instantiates the body. If you write a generic scale(T value, T factor) that multiplies its arguments and someone calls it with a std::string, the error points at the * operator deep inside your template, followed by a long instantiation trace. The declaration said nothing about what T must support, so the contract existed only in your head and in the documentation. Before C++20 the standard workaround was SFINAE: abusing std::enable_if in a defaulted template parameter so that a failing condition quietly removed the overload. It worked, but the contract was hidden inside a type trick, and the diagnostics were poor. Concepts were designed over many years and became part of the language in C++20, and GCC 13 on Ubuntu 24.04 supports them with -std=c++20.

A turns the hidden contract into a named, reusable declaration. The standard library ships a set of them in the header <concepts>, including std::integral<T> and std::floating_point<T>. You can combine them into your own:

cpp
#include <concepts>

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

template <Numeric T>
T clamp_value(T v, T lo, T hi) {
    if (v < lo) return lo;
    if (v > hi) return hi;
    return v;
}

Numeric<int> and Numeric<double> are true; Numeric<std::string> is false. The concept is evaluated entirely at compile time and produces no run-time code. Using Numeric T in the template parameter list is one of three equivalent ways to attach the constraint:

cpp
template <std::floating_point T>
T half_a(T v) { return v / 2; }              // constrained parameter

template <typename T>
    requires std::floating_point<T>          // requires clause
T half_b(T v) { return v / 2; }

template <typename T>
T half_c(T v) requires std::floating_point<T> // trailing requires clause
{ return v / 2; }

A accepts any constant boolean expression, not just a concept name: requires (sizeof(T) >= 4) is legal. The three positions above mean exactly the same thing; teams usually pick the constrained-parameter form for single concepts and the clause form when combining several conditions with && and ||.

When a call violates the constraint, the candidate is removed from the overload set before its body is ever instantiated. If no candidate remains, GCC 13 reports the failure at the call site and its notes say "constraints not satisfied", naming the concept and the specific requirement that failed. Compare that with the pre-concepts trace through the template body: the diagnostic now speaks in terms of your contract, not your implementation.

std::integral includes bool and char

std::integral<T> is true for bool, char, wchar_t and the fixed-width integer types, not just int and long. If your numeric library must exclude bool, add && !std::same_as<T, bool> to your own concept rather than assuming std::integral means "a number you can do arithmetic on". Also note that std::integral<const int> is true as well, because the trait ignores cv-qualifiers.

Because concepts are constant expressions, you can assert them directly, which is the cheapest way to pin down an API contract:

cpp
static_assert(Numeric<int>);
static_assert(Numeric<double>);
static_assert(!Numeric<const char*>);

These checks run on every build, cost nothing at run time, and double as executable documentation of what the library accepts.

Going deeperWhen constraints are checked, and why satisfaction is cheap

Constraint checking happens during overload resolution, after the template arguments are deduced and before the function body is instantiated. Two properties keep this affordable. First, compilers cache satisfaction results: once GCC has evaluated Numeric<int>, later uses of that concept with the same argument reuse the result. Second, && and || in a constraint short-circuit left to right, and an unevaluated right operand is never checked:

cpp
template <typename T>
concept SizedOrIntegral =
    std::integral<T> || requires(T t) { t.size(); };

For int, the left side is true, so the compiler never even forms the requirement t.size(), which would be invalid for int. This is what makes defensive concept composition safe: you can guard a syntactic requirement behind a cheaper semantic one.

SFINAE tricks vs C++20 conceptsSFINAE(enable_if)C++20conceptsContract livesina defaultedparametertricka namedrequiresclauseFailed typesilentremoval,crypticerrorsnamedconstraint indiagnosticOverloadorderingmanual tagdispatchautomaticsubsumptionReadable bytemplateexpertsany C++reader
The same contract expressed as an enable_if trick and as a named concept, and what changes for the reader and the diagnostic
02

Requires expressions: four kinds of requirement

3 min read

Library concepts like std::integral describe categories of types. Your own contracts usually need something more specific: "this type has a calibrate() member, a nested value_type, and a read() that is noexcept and returns something usable as an int". That is written with a . Here is one using all four kinds of requirement:

cpp
#include <concepts>

template <typename T>
concept Sensor = requires(T s, const T cs) {
    s.calibrate();                                        // simple
    typename T::value_type;                               // type
    { cs.read() } noexcept -> std::convertible_to<int>;   // compound
    requires sizeof(T) <= 64;                             // nested
};

The parameters s and cs are placeholders that exist only inside the braces. They have no storage, no definitions are needed, and no expression in the body is ever evaluated: the compiler only checks that each requirement would be well-formed. That is why you can write requirements against member functions you have merely declared.

A simple requirement is an expression followed by a semicolon. It demands only that the expression is valid: s.calibrate(); passes if the member exists and is callable, regardless of its return type. A type requirement is typename followed by a type name; it demands that the type exists. typename T::value_type; passes for a class with that nested alias and fails for one without it.

A compound requirement wraps an expression in braces and adds up to two extra checks: { expr } noexcept -> SomeConcept;. It verifies three things in order: the expression is valid, if noexcept is present the expression is known not to throw, and if a trailing -> Concept is present the deduced type satisfies that concept. The trailing concept receives decltype((expr)) as its first argument, so value category matters: a read() returning int by value deduces int, but one returning int& deduces int&, and std::same_as<int> would then fail. Using std::convertible_to<int> as above accepts both, which is usually what an API contract wants.

A nested requirement is the keyword requires followed by a constant expression that must be true. requires sizeof(T) <= 64; checks a property, not an operation. The distinction to remember: a simple requirement asks "is this expression valid?", a nested requirement asks "is this condition true?". You will often see nested requirements used to check another concept: requires std::same_as<typename T::value_type, int>;.

All requirements must hold for the requires expression to yield true, and requirements are checked in order; the first failure stops the check. Because the whole expression is a bool, it composes with everything from the previous section, and it pairs naturally with static_assert to enforce an API contract at compile time:

cpp
struct GoodSensor {
    using value_type = int;
    void calibrate();
    int read() const noexcept;
};
struct BadSensor {
    using value_type = int;
    void calibrate();
    int read() const;            // not noexcept
};

static_assert(Sensor<GoodSensor>);
static_assert(!Sensor<BadSensor>);

Only declarations are needed: the requires expression never calls anything. BadSensor fails the compound requirement because read() can throw, and the static_assert turns that into a build error the moment someone weakens the contract.

There is one more spelling you will meet in real code: the requires requires idiom. A requires clause can take an anonymous requires expression directly, without defining a concept first:

cpp
template <typename T>
    requires requires(T a, T b) { { a + b } -> std::convertible_to<T>; }
T add(T a, T b) { return a + b; }

The first requires introduces the clause; the second begins the expression that produces its boolean value. It is legal and occasionally handy for a one-off constraint, but prefer a named concept whenever the constraint is reused or worth documenting: a name appears in diagnostics, and, as the last section shows, only named concepts can order overloads.

Four kinds of requirementSimples.calibrate();expression isvalidTypetypenameT::value_type;type existsCompound{ cs.read() }noexcept ->...valid,noexcept,return typeNestedrequiressizeof(T) <=64;condition istrueAll must hold; nothing is ever evaluated.
The four kinds of requirement inside a requires expression, with an example and the question each one answers
03

Constrained auto and abbreviated function templates

3 min read

C++20 lets you combine the two ideas above into the shortest constrained form the language has ever offered:

cpp
void log_reading(std::integral auto value);

This is an . The declaration is exactly equivalent to:

cpp
template <std::integral T>
void log_reading(T value);

The rules follow from that equivalence. Each auto introduces a separate invented parameter, so a function with two constrained auto parameters accepts two independent types, and the invented parameters cannot be referred to by name inside the body (use the full template form when you need the type, for example to declare a local of type T). Deduction works as for any function template, and a call whose deduced type fails the concept removes the candidate, with the same clean diagnostic as before.

Constrained auto also works on return types, where it checks the deduced return value against the concept:

cpp
std::floating_point auto ratio(std::integral auto count,
                               std::integral auto total) {
    return static_cast<double>(count) / static_cast<double>(total);
}

Here ratio(3, 4) deduces two independent integral parameter types and returns double, which satisfies std::floating_point. If you changed the body to return an integer, the return constraint would fail at the definition, not at some distant call site. This is a compact way to build the generic numeric library this lesson prepares: scale, clamp_value and ratio can each be written either as template <Numeric T> or with Numeric auto parameters, and both forms enforce the same contract.

Two more positions accept constrained placeholders. A variable declaration can constrain the deduced type:

cpp
std::integral auto samples = 128;   // ok
// std::integral auto ratio2 = 0.5; // error: double is not integral

And a generic lambda can constrain its parameters, which is often the neatest way to write a small constrained callback:

cpp
auto twice = [](std::integral auto v) { return v + v; };
twice(21);      // ok
// twice(2.5);  // error: constraint std::integral not satisfied
Pick one style per library

The abbreviated form is ideal for short free functions and lambdas. When the body needs the parameter's type name, when several parameters must share one type (clamp_value(v, lo, hi) all being T), or when you want a trailing requires clause combining conditions, use the explicit template form. Mixing both freely is legal but makes a header harder to scan.

04

Subsumption: ordering constrained overloads

4 min read

Concepts do more than reject bad types: they give overload resolution a principled way to choose between two templates that both accept the argument. Consider a general numeric case and a more specific signed case:

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

template <typename T>
concept SignedArithmetic =
    Arithmetic<T> && std::signed_integral<T>;

template <Arithmetic T>
const char* kind(T) { return "arithmetic"; }

template <SignedArithmetic T>
const char* kind(T) { return "signed arithmetic"; }

kind(42) calls the second overload, kind(42u) and kind(2.5) call the first. Without concepts you would implement this ordering by hand with tag dispatch or enable_if conditions that explicitly exclude each other. Here the compiler derives it: SignedArithmetic subsumes Arithmetic, so when both candidates are viable and otherwise equally good, the more constrained one wins. This mechanism is called .

To see why it works, you need . The compiler does not reason about arithmetic or prove logical implications; it compares normalized structure.

Step by stepHow a constraint is normalized and compared
  1. Split connectives: && becomes a conjunction, || becomes a disjunction of the normalized operands.

  2. Expand concept names: a concept-id like Arithmetic<T> is replaced by its definition's normalized body, with T mapped to the argument.

  3. Reach atomic constraints: each leaf is an atomic constraint: one source-level expression plus its parameter mapping.

  4. Compare structurally: identical atomic constraints subsume each other; a conjunction A && B subsumes A; and A subsumes a disjunction A || B that contains it.

Apply that to the example. Arithmetic<T> normalizes to the disjunction of two atoms: std::integral<T> or std::floating_point<T>. SignedArithmetic<T> normalizes to a conjunction of that same disjunction and the atom std::signed_integral<T>. A conjunction subsumes anything one of its parts subsumes, and its first part is structurally identical to the other overload's whole constraint. So SignedArithmetic subsumes Arithmetic, and the signed overload is more constrained. Note the direction: Arithmetic does not subsume SignedArithmetic, because an integral-or-floating disjunction does not guarantee signedness.

Going deeperWhy identical atoms require named concepts

Two atomic constraints are identical only if they come from the same source-level expression with equivalent parameter mappings. In practice that means the same concept definition: every use of Arithmetic<T> expands to atoms originating in the one definition of Arithmetic. (This also holds for library concepts: two uses of std::integral<T> expand to the same atom from its definition, and GCC 13 orders overloads that spell std::integral<T> || std::floating_point<T> inline; this was checked with GCC 13.) The trouble starts when the repeated text is a raw expression, such as a type trait. If you write the constraint inline on both overloads:

cpp
template <typename T>
    requires (std::is_integral_v<T> || std::is_floating_point_v<T>)
const char* kind(T);

template <typename T>
    requires (std::is_integral_v<T> || std::is_floating_point_v<T>)
              && std::is_signed_v<T>
const char* kind(T);

the two std::is_integral_v<T> expressions sit at different source locations, so they are different atoms. Nothing subsumes anything, and kind(42) is ambiguous (GCC 13 reports call of overloaded 'kind(int)' is ambiguous). The expressions look identical to a human, but subsumption is structural, not textual or logical. This is the strongest practical argument for naming every reusable constraint: the name is what makes the atoms identical, and identity is what makes ordering work. The same normalization also drives the choice between constrained class template partial specializations, which you will meet again when templates get more advanced.

SignedArithmetic after normalizationSignedArithmetic<T>conjunctionArithmetic<T>disjunction, shared atomsstd::integral<T>std::floating_point<T>std::signed_integral<T>SignedArithmetic<T>conjunctionArithmetic<T>disjunction, shared atomsstd::integral<T>std::floating_point<T>std::signed_integral<T>
SignedArithmetic normalized: a conjunction of the Arithmetic disjunction and std::signed_integral, sharing atoms with Arithmetic

You now have the full vocabulary of C++20 template contracts: concepts name requirements, requires clauses attach them, requires expressions describe them operation by operation, constrained auto shortens the common cases, and subsumption orders the overloads. The next lesson, "Sequence containers and memory layout", answers how std::vector, std::array and std::deque store their elements in memory, and you will see the standard library stating its own contracts with exactly these tools.

Key takeaways

  • A concept is a named compile-time predicate on types, checked before the template body is instantiated
  • A requires expression holds four kinds of requirement (simple, type, compound, nested) and is never evaluated
  • Each constrained auto parameter invents a separate template parameter, so abbreviated templates are full templates
  • Subsumption orders overloads only through identical atomic constraints, which is why named concepts matter
Reflect
  1. Explain to a colleague, in two sentences: define a concept and use it to constrain a template in all three syntactic positions
  2. Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
  3. What surprised you when you ran the commands yourself?
On a real board

Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.

References and further reading

Find your next step

↑ ↓ to move · Enter to open · Esc to close