Concepts in C++20

Combining Concepts with Logical Operators

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

Abstract art representing computer hardware

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.

Answers to questions are automatically generated and may not have been reviewed.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 125 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved