2

I'm new to programming and I'm trying to review this C++ primer book, however while checking LAMBDA part I get into a compile error on my Visual studio 2022.

#include <algorithm>
#include <iostream>

using namespace std;

int main()
{
    int i = 10;
    if ([&]()->bool { while(i) --i; return true; })
        cout << "the captured variable is 0" << endl;

    return 0;
}

Appreciate your enlightenment...

gaofeng
  • 393
  • 1
  • 3
  • 11

2 Answers2

3

The lambda returns a bool value when called. But the code is not calling the lambda at all. It is instead trying to evaluate the lambda object itself in a boolean context, which is not a valid operation since a lambda's generated type does not define a conversion of a lambda object to a bool.

You need to actually call the lambda first (ie, invoke the lambda type's function call operator) by placing () after the lambda object, and then evaluate its return value afterwards, eg:

int main()
{
    int i = 10;
    if ([&]()->bool { while(i) --i; return true; }())
                                               // ^ add this !
        cout << "the captured variable is 0" << endl;

    return 0;
}

Coding a lambda inside an if statement is not a good idea, though. It is legal, but it makes the code harder to read and understand. It would be better to assign the lambda to a variable first, and then call it afterwards, eg:

int main()
{
    int i = 10;
    auto lambda = [&]() -> bool { while(i) --i; return true; };
    if (lambda())
        cout << "the captured variable is 0" << endl;

    return 0;
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
0
if ([&]()->bool { while(i) --i; return true; })

The lambda is not called there. Try

if ([&]()->bool { while(i) --i; return true; }())

It might be a misprint in the book. I can't find it on C++ Primer Errata.

273K
  • 29,503
  • 10
  • 41
  • 64