David David - 3 months ago 7
C++ Question

Is there a way to write a lambda expression inside an IF with everything captured?

It's my understanding that if I use the syntax [&] in a lambda expression, then my lambda expression has access to surrounding variables and parameters of the function.

Therefore, I tried to write the following (simplified) code

if ( [&]()
{
bool b = false;
return b;
}
)
{
// Do something in TRUE part of if statement
}


but I get the error "Value of type 'lambda at...' is not contextually convertible to 'bool'

Would appreciate some insight into this issue.

Many thanks,
D

Answer

You need to call the lambda you're constructing. It will not be called implicitly.

if ([&]() { /*...*/ return b; }()) {
    //                         ^^ call the lambda
    // ...
}
Comments