Lambda表达式可在if语句中返回布尔值 [英] Lambda expression to return bool in if statement
问题描述
仅此而已,我想使用<内部的lambda表达式返回 true
或 false
code> if()语句。我看到了与我的问题类似的问题: LINK 但我找不到答案。
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’
})
好,读取错误我以为我没有调用该函数,因为编译器不将该表达式视为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
错误:
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.
编辑:
请注意,我已经简化了代码,因此您可以轻松地复制错误。我知道在这种特殊情况下lambda表达式没有任何意义。
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.
推荐答案
您忘记了调用lambda。现在,您要说的是 if(function_pointer)
,因此编译器无法将其转换为布尔表达式。
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.
带有布尔lambda的简单 if
子句的写法是:
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
}
或
if([&rel_pose]()
{
return (sqrt(rel_pose(0) * rel_pose(0) + rel_pose(1) * rel_pose(1)) < 2) ? true : false;
}()){
//do sth
}
在这种情况下是否需要lambda是有问题的,您可以摆脱lamdba,将布尔表达式保留在if子句。在谈论它时-无需在此处使用三元运算符。 返回sqrt(rel_pose(0)* rel_pose(0)+ rel_pose(1)* rel_pose(1))< 2;
就足够了,而且更具可读性。
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.
这篇关于Lambda表达式可在if语句中返回布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!