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
