Probably the two most useful features added to C++20 are requires and requires. They make it so much easier to control overload resolution, and when c

if constexpr requires requires { requires }

submited by
Style Pass
2024-10-24 10:00:05

Probably the two most useful features added to C++20 are requires and requires. They make it so much easier to control overload resolution, and when combined with if constexpr in C++17, they allow basic reflection-based optimizations in templates. While requires requires has gotten a lot of (negative?!) press for controlling overload resolution, its cousin requires { requires } is a bit overlooked.

C++20 added requires, a way to enable or disable a function overload based on some compile-time condition. For example, consider a facility for producing debug output of types for error reporting:

The two overloads with the requires clause are only enabled for integers or floating point types, respectively, and are not considered otherwise. Additionally, overload resolution is smart: It knows that we want the overload with the most specific requirements, and it will only pick the first function when no other overload matches. This is also where concept comes in: A concept is simply a way to name a group of requirements that affects the search for more specific requirements. The technical term for that is subsumption. Because creating named requirements with concept also comes with additional syntax sugar, you don't need requires—so this blog post is gonna ignore concept. In general, if you would use a concept in only one place, it is too early to introduce it.

requires is another new feature for C++20 that allows us to check whether a condition is well-formed, instead of forcing us to rely on SFINAE. For example, let's say we're implementing a generic cont_assign(container, rng) for every container with .push_back():

Leave a Comment