Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambda function throwing error if return type is changed from auto to bool

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?

like image 395
Deep Avatar asked Aug 06 '26 13:08

Deep


2 Answers

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.

like image 111
songyuanyao Avatar answered Aug 08 '26 08:08

songyuanyao


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.

like image 40
kesarling He-Him Avatar answered Aug 08 '26 06:08

kesarling He-Him



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!