[英]How to create an inline scope with return value in c++?
I have a larger if
expression let's say of the kind 我有一个更大的if
表情,比如说那种
if (a && (c(b.getObject()) || d(b.getObject()))
{
...
}
is there a way to declare b.getObject()
as local reference only if a
is true
? 仅当a
为true
才可以将b.getObject()
声明为本地引用吗? I'm looking for a kind of lambda function perhaps like this: 我正在寻找一种lambda函数,也许像这样:
if (a && { Object & o(b.getObject()); return (c(o) || d(o))} )
{
...
}
but this obviously doesn't work. 但这显然行不通。 Of course I could nest it in another if
block, but is there a more "local" way to do it? 当然,我可以将其嵌套在另一个if
块中,但是还有一种“本地”方式可以做到吗?
edit: 编辑:
One argument against nested if
blocks is that they do not allow one combined else
block. 反对嵌套if
块的一个论点是它们不允许一个合并else
块。
Define a function that does the two checks, and call it so you only evaluate b.getObject()
once. 定义一个执行两次检查的函数,然后调用它,以便仅对b.getObject()
一次评估。
auto e = [](const Object& o) { return c(o) || d(o); };
if (a && e(b.getObject()))
{
...
}
Prior to C++11 you would have to write e
as a function at namespace scope, or as a variable of a local class type with an operator()
. 在C ++ 11之前,您必须将e
作为名称空间范围内的函数编写,或者作为带有operator()
的本地类类型的变量编写。
Also, G++ has a non-standard "statement expression" extension that allows what you want, with slightly different syntax: 另外,G ++具有非标准的“语句表达式”扩展名,该扩展名允许您使用略有不同的语法进行所需的操作:
if (a && ({ const Object& o = b.getObject(); c(o) || d(o); }))
{
...
}
However, I think generally a nested if
is much cleaner and easier to read than either of these alternatives. 但是,我认为一般而言,嵌套的if
比这两种方法中的任何一种都更清洁,更易于阅读。
Please don't do this, but it works... 请不要这样做,但是它可以工作...
Object x;
if (a && (x = b.getObject(), c(x) || d(x)))
{
}
You may use a lambda for that: 您可以为此使用lambda:
if (a && [&b](){ const Object& o = b.getObject(); return c(o) || d(o); }() ) {
...
}
but declaring the function outside the condition seems cleaner. 但是在条件之外声明该函数似乎更简洁。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.