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?

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.

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.

Difference between requires keyword and requires expression
What is the difference between the requires keyword and a requires expression in C++20 concepts?
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