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.
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.
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.
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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With