Difference between requires keyword and requires expression

What is the difference between the requires keyword and a requires expression in C++20 concepts?

The requires keyword and requires expressions serve different purposes in C++20 concepts:

The requires keyword is used within a requires expression to assert that a specific expression must be valid and evaluate to true for a type to satisfy the concept. For example:

template <typename T>
concept Addable = requires(T a, T b) {
  requires std::is_arithmetic_v<T>;
  requires requires { a + b; };
};

Here, the requires keyword is used to assert that T must be an arithmetic type and that the expression a + b must be valid.

A requires expression, on the other hand, is a way to group multiple requirements together. It consists of a parameter list and a body containing one or more requirements. A type satisfies the requires expression if all the requirements in its body are met. For example:

template <typename T>
concept Printable = requires(T a) {
  std::cout << a;
};

In this case, the requires expression states that for a type T to be Printable, the expression std::cout << a must be valid, where a is an instance of type T.

So, in summary, the requires keyword is used within a requires expression to assert individual requirements, while a requires expression is a way to group and define a set of requirements that a type must satisfy to meet a concept.

Creating Custom Concepts

Learn how to create your own C++20 concepts to define precise requirements for types, using boolean expressions and requires statements.

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Negating requires expressions in C++20 concepts
How can I negate a requires expression in a C++20 concept to specify that a type should not satisfy certain requirements?
Using multiple type parameters in C++20 concepts
Can I define a concept that takes multiple type parameters in C++20? How can I use such a concept to constrain a template?
Using requires clause in function templates
How can I use a requires clause in a function template to constrain its arguments based on a concept?
Using concepts to constrain auto parameters
Can I use concepts to constrain auto parameters in functions? How does it work?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant