Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++20: Concepts of multiple types and its constraint, correct syntax?

Tags:

It is confirmed that in the upcoming c++20 standard, according to this reddit report from the recent Cologne ISO C++ Meeting, we will be able to specify a template's concept and for each class/function template, we will be able to set the constraints on its types. However, in documentations and tutorials (e.g. here), I could not find the correct syntax for the multi-type use-case.


Suppose we have a multi-type concept:

template<typename T1, typename T2> concept AreEqComparable = requires(T1 a, T2 b) {     { a == b } -> bool; }; 

Let's say, I want to define a simple comparison function between two different types. How can I do that? More specifically, what should I write in the ??? part of the code below:

??? bool are_equal(T1 a, T2 b) { return a == b; } 

I couldn't find any reference to this case in here, here, and even here. I have randomly tried something like:

/* 1 */ template<AreEqComparable T1, T2> /* 2 */ AreEqComparable<T1, T2> /* 3 */ template<AreEqComparable<T1, T2>> 

But all of them throw syntax errors. I think the answer should lie somewhere in the specification P0557 by Bjarne Stroustrup, but I wasn't able to find it after a quick look.

like image 836
FalconUA Avatar asked Jul 11 '19 00:07

FalconUA


People also ask

What are the concepts in C ++ 20?

C++20 added abbreviated function templates which use auto as a placeholder type in the parameter declaration. A constrained placeholder type allows to put constraints on the automatically deduced return type of a function or a variable. C5 : A trailing requires-clause.

What is constraints in C++ with example?

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.

What are concepts CPP?

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!


1 Answers

You can write it like this:

template <typename T1, typename T2>     requires AreEqComparable<T1, T2> bool are_equal(T1 a, T2 b) {     // ... } 

Here, we use a requires-clause to impose a requirement on the type template parameters.

like image 171
L. F. Avatar answered Sep 23 '22 01:09

L. F.