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.
if constexpr requires requires { requires }
by Jonathan Müller
From the article:
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 whereconcept
comes in: Aconcept
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 withconcept
also comes with additional syntax sugar, you don't needrequires
—so this blog post is gonna ignoreconcept
. In general, if you would use aconcept
in only one place, it is too early to introduce it.
Add a Comment
Comments are closed.