Conecpts or what do you require?
Starting my regular blogging habit I do not want you to be bored out so I start with something that is new in C++20. C++20 is another big step forward to make templates even better. Or some would say a step into the so called meta-programming. But do not be scared by the meta it is not that complicated as you might have heard. For sure it can get complicated, but that is also true for non meta code.
I will provide you some examples where concepts might be useful and a short reminder what templates are, just in case.
Short reminder: templates
Just to make sure we are all on the same page, the basic thing we use templates for is as a cookie cutter. You do not buy a cookie cutter per dough and you do not want to repeat code.
template <typename T>
T add(T a, T b){
return a + b;
}
This example is simple enough to show you what we can do with it. We have a function template add
that takes two arguments of the same type, and applies the +
operator and return the value.
So how to use it?
void main(){
add(1, 3);
add(3.5F, 9.2F);
}
Simple isn’t it?
So why bother with concepts?
One of the answers you might get from people which crawled through other peoples compiler error messages a lot might be: To get better error messages. This is true. You can try it yourself. Just pass a custom type to the add
function (where the custom class does not implement the operator+
). If you have never seen such error messages before you might be thrilled to get one :). Once more this example is so simple and easy, also the error message you get is understandable.
Concepts are a good way to specify the template arguments your template accepts in a readable way and with better error messages.
How to do it?
It is not too hard. Besides this example there are a lot of predefined concepts you can use already available in the standard library.
Let me show a concept for the add function above:
template<typename T>
concept CompareableAddable = requires (T a, T b){
a + b == b + a
}
So what we require now is that the type passed has two things: an operator+
and an operator==
.
Note: Be aware that this does not mean, that it must have the same result. It just means the operation performed must be valid.
You can play around here: https://godbolt.org/z/3sooTaoTr