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;
}