On Tuesday, March 07, 2023 22:41 CET, "Jeanette C." <julien(a)mail.upb.de>
wrote:
Hey hey,
figuring out the syntax for c++20 concepts I run into challenges. With a two
parameter template concept like swappable_with or convertible_to is it always
necessary to use a requires statement like this:
template<typename T>
requires std::convertible_to<T,int>
void f(T t) ...
...
With single parameter concepts like integral a syntax like this will work:
template<std::integral T>
void f(T t)...
There are two ways of using concepts; in expressions (for example in 'requires'
clauses, but anywhere
else as a boolean variable template as well) and as type-constraint declarations for
template
parameters or deduced types of function parameters, return types, or variable types
('auto').
When you use them in expressions you need to provide all the template parameters, but when
you use them as type-constraints the actual type being constrained will be inserted
automatically as the first template parameter. In that case you should only provide the
rest of the template parameters starting at the second.
For example, these function templates are equivalent:
~~~
template <typename T> requires std::convertible_to<T, int>
void foo(T t) {}
template <std::convertible_to<int> T>
void foo(T t) {}
void foo(std::convertible_to<int> auto t) {}
~~~
In all three cases the compiler will enforce that the type of 't' is convertible
to 'int'.
It is documented for example here:
https://en.cppreference.com/w/cpp/language/constraints
...though it might require a bit of clicking around to find the various pieces.
--ll