Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambda expression to return bool in if statement

Tags:

c++

lambda

c++14

Just to get to the point, I want to return true or false using the lambda expression inside the if() statement. I saw this question which has similar question to mine: LINK but I could not find the answer.

So here is my example code:

if([&rel_pose](Eigen::VectorXd pose)
    {
        return (sqrt(pose(0) * pose(0) + pose(1) * pose(1)) < 2) ? true : false;
    }) // do smth

When I try to compile I get this error:

 error: could not convert ‘<lambda closure object>graphslam::GraphSLAM::main_pose_callback(const ConstPtr&)::<lambda(Eigen::VectorXd)>{rel_pose}’ from ‘graphslam::GraphSLAM::main_pose_callback(const ConstPtr&)::<lambda(Eigen::VectorXd)>’ to ‘bool’
  })

Ok, reading the error I thought that I did not call the function as the compiler does not treat the expression as bool. So I tried to use this code:

if(([&rel_pose](Eigen::VectorXd pose)
    {
        return (sqrt(pose(0) * pose(0) + pose(1) * pose(1)) < 2) ? true : false;
    };)) // do smth

And the error:

expected ‘)’ before ‘;’ token
  };)) return;

That might look like an obvious error but for me, I probably do not understand the syntax correctly and thought to ask what is happening.

EDIT: Please note that I have simplified the code so you can replicate the error easily. I know that lambda expression in this particular case does not make any sense.

like image 494
aikhs Avatar asked Dec 11 '22 03:12

aikhs


1 Answers

you forgot to call your lambda. Right now you're saying if(function_pointer) hence the compiler failing to convert that into a boolean expression.


A simple if clause with boolean lambda is therefore written like:

if ([]() {
    return true;
}()) {
    //do sth
}

You also have an error by having a variable be a parameter while simultaneously capturing it. You have to decide, so either:

if([](Eigen::VectorXd pose)
    {
        return (sqrt(pose(0) * pose(0) + pose(1) * pose(1)) < 2) ? true : false;
    }(rel_pose)){
    //do sth
}

or

if([&rel_pose]()
    {
        return (sqrt(rel_pose(0) * rel_pose(0) + rel_pose(1) * rel_pose(1)) < 2) ? true : false;
    }()){
    //do sth
}

The need of a lambda is in this case questionable, you could just get rid of the lamdba leaving the boolean expression in the if clause. When talking about it - no need to use a ternary operator here. return sqrt(rel_pose(0) * rel_pose(0) + rel_pose(1) * rel_pose(1)) < 2; is sufficient and more readable.

like image 143
Stack Danny Avatar answered Jan 11 '23 08:01

Stack Danny