The Trailing <requires> Clause

Get an overview of the trailing <requires> clause.

How to write trailing requires clause

We can also use the trailing requires clause that comes after the function parameter list (and any qualifiers, like const or override) and before the function implementation.

template <typename T>
auto add(T a, T b) requires Number<T> {
  return a+b;
}

This gives the same result as the requires clause; we just wrote it with different semantics. It still means that we can’t add two numbers of different types. We also need to modify the template definition as we did before:

template <typename T, typename U>
auto add(T a, U b) requires Number<T> && Number<U> {
  return a+b;
}

More constraints

Still, we face the drawback of scalability. Each new function parameter, potentially of a different type, needs its own template parameter.

Just as for the requires clause, we can express more complex constraints in the trailing requires clause.

template <typename T>
auto add(T a, T b) requires std::integral<T> || std::floating_point<T> {
  return a+b;
}

Get hands-on with 1200+ tech skills courses.