Boost lambda 困惑
为什么回调只调用一次?
bool callback()
{
static bool res = false;
res = !res;
return res;
}
int main(int argc, char* argv[])
{
vector<int> x(10);
bool result=false;
for_each(x.begin(),x.end(),var(result)=var(result)||bind(callback));
return 0;
}
Why is callback called once only?
bool callback()
{
static bool res = false;
res = !res;
return res;
}
int main(int argc, char* argv[])
{
vector<int> x(10);
bool result=false;
for_each(x.begin(),x.end(),var(result)=var(result)||bind(callback));
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
||
表达式短路 第一次bind
返回true
后。第一次评估
bind
时会被调用,因为这是确定false || 值的唯一方法。 绑定(...)
。 由于bind(...)
返回true
,因此result
设置为true
。每当你说
...
bind(...)
表达式不会被计算,因为它返回什么并不重要; 表达式true || Anything
始终为true
,并且||
表达式 短路。确保始终调用
bind
的一种方法是将其移动到||
的左侧,或者将||
更改为&&
,具体取决于您想要通过result
实现的目标。The
||
expression short circuits after the first timebind
returnstrue
.The first time you evaluate
bind
is called, because that's the only way to determine the value offalse || bind(...)
. Becausebind(...)
returnstrue
,result
is set totrue
.Every other time you say
... the
bind(...)
expression isn't evaluated, because it doesn't matter what it returns; the expressiontrue || anything
is alwaystrue
, and the||
expression short circuits.One way to ensure that
bind
is always called would be to move it to the left side of the||
, or change the||
to an&&
, depending on what you are trying to accomplish withresult
.在您的特定示例中,Boost.Lambda 并没有真正为您带来任何好处。 去掉 lambda 部分,也许你会更清楚地看到发生了什么:
这仍然依赖于你知道
||
运算符是短路的,如 丹尼尔解释了。In your particular example, Boost.Lambda doesn't really gain you anything. Get rid of the lambda parts, and maybe you'll see more clearly what's going on:
This still relies on you to know that the
||
operator is short-circuited, as Daniel explained.