liveBook · Manning

Requires clause

As explained in Learn C++ by Example

A requires clause is C++ syntax that constrains a declaration or definition with compile-time requirements.

A requires clause constrains a declaration or definition with compile-time requirements. It works with concepts to state what a template argument must support and produces clearer errors when constraints are not satisfied. section 4.2.4

A requires clause helps you:

  • Name a requirement such as “T provides a Quack function” with a concept. section 4.2.4
  • Attach that requirement to a function template before its declaration. section 4.2.4
  • Replace indirect template failures with diagnostics stating that associated constraints are not satisfied. section 4.2.4

Constraining a duck

Define `Quacks` with `requires(T t) { t.Quack(); }`, then declare `must_be_a_duck` with `requires Quacks<T>`. Calling it with `42` fails because the requirement is not satisfied. section 4.2.4

Listing 4.6 Writing and using a concept
template<typename T>
concept Quacks = requires(T t)    #1
{
    t.Quack();                    #2
};
 
template<typename T>
requires Quacks<T>                #3
void must_be_a_duck(T x)
{
    x.Quack();
}

Inspect the complete concept and constrained-function listing, including the required expression and the requires clause. section 4.2.4

How Learn C++ by Example covers it

How deep it goes
Defines concepts and constrained signatures, then connects requirements to clock checks, but does not develop formal constraint mechanics.
Examples
Uses a Quack-based duck concept, invalid int calls, and std::chrono::is_clock<int> to demonstrate failed requirements.
What it assumes
Assumes templates and member expressions while teaching named requirements through a small Quack example.
What you can do after
Apply it via C++20 concepts to constrain functions and obtain more precise compile-time errors.
How it connects
Connects concepts, templates, type traits, clock requirements, and std::chrono.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn C++ by Example. The section links point to the parts of the book it draws on.