[LAD] Re: [LAD] [semi-OT} c++20 concepts and syntax

"Lars Luthman" <[email protected]>
Newsgroups gmane.linux.audio.devel
Message-ID <7900-6408c180-37-b0975c0@229494192>
On Tuesday, March 07, 2023 22:41 CET, "Jeanette C." <julien-3g/[email protected]> 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
_______________________________________________
Linux-audio-dev mailing list -- linux-audio-dev-cunTk1MwBs/[email protected]
To unsubscribe send an email to linux-audio-dev-leave-cunTk1MwBs/[email protected]
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.