About limitations and concepts

I really don't understand why C ++ 20 provides such a function. I think this is redundant , yes, I'm sure I'm wrong, but I need someone to indicate why I am wrong and how to use this function gracefully. Here is an example:

template<typename T> concept LessCompareable=requires(const T& lhs, const T& rhs) { {lhs<rhs}->bool; }; 

Now I have defined the concept. Then I will restrict the function template as follows: (well, let's call it comp, in fact it is exactly the same as std::min )

 template<typename T> const T& comp(const T& a , const T& b) requires LessCompareable<T> {return a<b?a:b;} 

So the problem is that you call it like

 std::thread a,b; cout<<comp(a,b); 

Error Execution Error

but if we do not use the restriction, CE will happen too.

So, this puzzles me, both of them have CE, then why should I use restrictions?

+5
source share
2 answers

The purpose of the constraints is to enable you to specify prerequisites for operations using built-in language constructs. These prerequisites can be checked by the compiler and either:

  • An error message will appear.
  • Congestion will not be taken into account when permitting congestion (yes, another way to do SFINAE).

The error messages are nice, but the new prerequisites for # 2 are the real meat of this. What you need to do before C ++ 20 gets the same effect looks something like this:

 template<typename T, std::enable_if_t<has_less_than_op<T>::value, int> = 0> const T& comp(const T& a , const T& b) {return a<b?a:b;} 

This is awkward and cumbersome. Patterns have this power, but this is a historical coincidence. Concepts (lite) and limitations make it possible to express the same thing in a more natural way.

Compare the above with your OP or this:

 template<LessCompareable T> const T& comp(const T& a , const T& b) {return a<b?a:b;} 

Which of the alternatives expresses things clearly? Not an old technique, I would say.

+13
source

One important feature of the concept, unlike existing methods, is to reduce compilation errors to the time of determination and the time of creation. Currently, all errors are generated when creating the template, and it is difficult to determine whether the definition of the template is poorly formed and never compiles or prepares the parameters. The main goal of the concept is to separate two types of errors.

+1
source

Source: https://habr.com/ru/post/1276263/


All Articles