Advertisement
Intermediate C++, Concepts & Constraints

What is a requires expression?

Short answer

A requires expression (requires(T a){ ... }) is a compile-time check that yields true if the enclosed operations/requirements are valid for the given types. It's used to define concepts, listing required expressions, their validity, and return-type constraints.

Save C++ mock interview
Advertisement
AModel answer
A requires expression (requires(T a){ ... }) is a compile-time check that yields true if the enclosed operations/requirements are valid for the given types. It's used to define concepts, listing required expressions, their validity, and return-type constraints. It replaces verbose SFINAE with readable requirement lists.
template <class T>
concept Addable = requires(T a, T b) { { a + b } -> std::same_as<T>; };
Real-world example
A custom Addable concept is defined with a requires expression listing that a + b must be valid and return T.
Likely follow-ups
  • What does a requires expression evaluate to? | How does it define a concept?
Related topics