Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++20 concept syntax - what does the requires parameter variables mean?

Many articles give examples like this:

template<typename T>
concept Equal = requires(T a, T b) {
    { a == b } -> std::same_as<bool>;
};

Does it make any difference if I write:

template<typename T>
concept Equal = requires(T a) {
    { a == a } -> std::same_as<bool>;
};

If it doesn't, why was the syntax designed like this? Why do they ask me to declare these variables like a or b?

Why do I need multiple variables of the same type? And why do I even need variables?

template<typename T>
concept Equal = requires {
    { declval<const T&>() == declval<const T&>() }
        -> std::same_as<bool>;
};
like image 925
RnMss Avatar asked Oct 08 '20 07:10

RnMss


People also ask

What is c++ 20 Concepts?

Concepts are a revolutionary approach for writing templates! They allow you to put constraints on template parameters that improve the readability of code, speed up compilation time, and give better error messages. Read on and learn how to use them in your code!

What is meant by constraints in c++?

A constraint is a requirement that types used as type arguments must satisfy. For example, a constraint might be that the type argument must implement a certain interface or inherit from a specific class. Constraints are optional; not specifying a constraint on a parameter is equivalent to using a Object constraint.


Video Answer


1 Answers

Why do they ask me to declare these variables like a or b? Why not even something like..

You aren't asked or required to use the variables. You are given the option because it's much more readable. There's little difference, as far as checking the constraints goes.

The reason the articles give examples like that one you cite, is because it's easier for humans to understand. The Equal concept is defined to read "given two hypothetical objects of this type, we can write a comparison expression with them, that results in a bool". That's it. You don't have to use this notation, you can write it with as much verbosity as you want.

But the old bit of wisdom about code still holds. Code is meant to be read far more than written, and not just in ways we foresee. When your concept is not satisfied in a context that results in a compiler error about a violated constraint, the compiler is likely to include the constraint in its error message. Which version of the concept is going to produce the easier-to-understand error message? My bet is on the one that uses helper variables.

like image 106
StoryTeller - Unslander Monica Avatar answered Oct 15 '22 01:10

StoryTeller - Unslander Monica