I was practicing lambda functions in C++, following code works fine
void insertionSort(int* a, int size, bool reverse=false) {
auto comp = [](int a, int b, bool reverse) {
return reverse ? a > b : b < a;
};
for (int i = 0; i < size; i++) {
int current = a[i];
cout << current <<endl;
int j = i-1;
while (j >= 0 && comp(current, a[j], reverse)) {
a[j+1] = a[j]; //shift right
j--;
}
a[j+1] = current;
}
show(a, size); //another function which prints all elements of a
}
but if I change
auto comp = [](int a, int b, bool reverse) {
with
bool comp = [](int a, int b, bool reverse) {
GCC compiler throws following error while compiling
error: 'comp' cannot be used as a function 29 | while (j >= 0 && comp(current, a[j], reverse)) {
So is this expected? What is general rule? Shall I always specify return type as auto
?
In the 1st code snippet, comp
's type is the type of the lambda, it's a unique unnamed class type, (that's why we use auto
, we can't specify the type explicitly). Note that it's not the return type of the lambda (i.e. bool
).
If you want to specify the return type of the lambda explicitly you can
auto comp = [](int a, int b, bool reverse) -> bool {
// ^^^^^^^
BTW: Non-capturing lambdas could convert to function pointer and then convert to bool
implicitly. So if you change the type of comp
to bool
its value is always true
. As the error message said, you just can't use it as functor.