In C++20 concepts, you can negate a requires
expression using the !
operator to specify that a type should not satisfy certain requirements. This is useful when you want to enforce that a type does not have a particular property or does not support a specific operation.
Here's an example that demonstrates negating a requires
 expression:
#include <concepts>
#include <iostream>
template <typename T>
concept NotAddable = !requires(T a, T b) {
a + b;
};
template <NotAddable T>
void add(T a, T b) {
std::cout << "Cannot add values of this type\n";
}
template <typename T>
void add(T a, T b) {
std::cout << "Result: " << a + b << '\n';
}
int main() {
add(1, 2);
add("Hello", " world");
}
Result: 3
Cannot add values of this type
In this example, the NotAddable
concept is defined using a negated requires
expression. It specifies that a type T
satisfies the concept if the expression a + b
is not valid for instances a
and b
of type T
.
The first overload of the add
function is constrained by the NotAddable
concept, so it will be called when the provided type does not support the +
operator. The second overload is unconstrained and will be called for types that do support the +
 operator.
As you can see, the negated requires
expression allows us to specify that a type should not satisfy certain requirements, providing a way to handle types that do not support specific operations or have certain properties.
Answers to questions are automatically generated and may not have been reviewed.
Learn how to create your own C++20 concepts to define precise requirements for types, using boolean expressions and requires
statements.