requires expressions and requires clauses in C++20

submited by
Style Pass
2022-06-21 18:30:10

The C++20 standard added constraints and concepts to the language. This addition introduced two new keywords into the language, concept and requires. The former is used to declare a concept, while the latter is used to introduce a requires expression or a requires clause. These two could be confusion at first, so let’s take a look at which is which and what is their purpose.

A requires expression is a compile-time expression of type bool that describes the constraints on one or more template arguments. There are several categories of requires expressions:

In this example, the as_string function is an uniform interface to serialize objects to string. For this purpose, it uses either the std::to_string function or the overloaded output stream operator <<. To select between these, two requires expressions are used; their purpose is to identify whether the expressions std::to_string(x) or os << x are valid (where x is a T) and what is their return type. As a result, calling as_string(42) and as_string(point{1, 2}) are both successful, but as_string(std::pair<int, int>{1, 2}) triggers a compiling error because neither of the two requires expressions is evaluated to true.

A requires clause is a way to specify a constraint on a template argument or function declaration. The requires keyword must be followed by a constant expression. The idea is though, that this constant expression should be a concept or a conjunction/disjunction of concepts. Alternatively it could also be a requires expression, in which case we have the curious syntax requires requires expr (that we’ve seen in the image above).

Leave a Comment