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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With