I just learned that C++20 provides three ways of applying constraints to a template:
I successfully used constrained template parameters and I tend to prefer that syntax. Still I wonder why there are three ways defined in the standard.
Are there fundamental technical differences? Do these flavors have unique advantages or disadvantages (other than syntactical appearance)?
There are no technical differences.
// (1)
void foo(Concept auto&& x);
means exactly the same thing as:
// (2)
template <Concept T>
void foo(T&& x);
means exactly the same thing as:
// (3)
template <typename T> requires Concept<T>
void foo(T&& x);
means exactly the same thing as:
// (4)
template <typename T>
void foo(T&& x) requires Concept<T>;
... but just pick one and use it consistently for the same function (can't declare with one syntax and define with another).
And there are reasons for each of them to exist - (1) is shorter than (2) but (2) gives you the name of the type - which you can then use in other places. (2) is shorter than (3) and (4), but (3) and (4) are more general and allow more kinds of constraints. (3) and (4) seem the same, but (4) is necessary for member functions of class templates and also gives you access to parameter names.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With