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.