Combining Concepts with Logical Operators

Can I combine multiple concepts using logical operators in a requires clause?

Yes, you can combine multiple concepts using logical operators like && (and) and || (or) in a requires clause. This allows you to specify more complex constraints on template parameters. Here's an example:

#include <concepts>
#include <string>

template <typename T>
requires std::integral<T>
  || std::floating_point<T>
T add(T a, T b) {
  return a + b;
}

int main() {
  // Valid, int is an integral type
  int intResult = add(5, 3);

  // Valid, double is a floating-point type
  double doubleResult = add(2.5, 1.7);

  // Invalid
  std::string strResult = add("Hello", "World");
}
error: 'add': no matching overloaded function found
could be 'T add(T,T)'
the associated constraints are not satisfied
the concept 'std::integral<const char*>' evaluated to false

In this example, the add function template is constrained to accept types that are either integral or floating-point using the || operator in the requires clause. This allows the function to be called with both int and double arguments, but not with std::string.

Concepts in C++20

Learn how to use C++20 concepts to constrain template parameters, improve error messages, and enhance code readability.

Questions & Answers

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

Using Concepts with Class Templates
How can I use concepts to constrain the types allowed for a class template?
Using Type Traits in Requires Clauses
Can I use type traits in a requires clause to constrain template parameters?
Concepts and Abbreviated Function Templates
How can I use concepts with abbreviated function templates?
Using Trailing Requires Clauses
What are trailing requires clauses and when should I use them?
Benefits of Using Concepts
What are the main benefits of using concepts in C++20?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant