Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between the three ways of applying constraints to a template?

I just learned that C++20 provides three ways of applying constraints to a template:

  • Requires Clause
  • Trailing Requires Clause
  • Constrained Template Parameter

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)?

like image 871
Silicomancer Avatar asked Jan 26 '23 01:01

Silicomancer


1 Answers

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.

like image 133
Barry Avatar answered May 12 '23 22:05

Barry