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)) {
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 (ie 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.
When you write auto comp = [](int a, int b, bool reverse) {
, comp has the unique type lambda aka, C++ compiler creates a struct names comp. But when you write bool comp = [](int a, int b, bool reverse) {
, comp has the type bool and can only take bool values.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.