Boost lambda 困惑

发布于 2024-07-15 12:33:33 字数 304 浏览 4 评论 0原文

为什么回调只调用一次?

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

暮凉 2024-07-22 12:33:35

|| 表达式短路 第一次 bind 返回 true 后。

第一次评估

result = result || bind(...)  // result is false at this point

bind 时会被调用,因为这是确定 false || 值的唯一方法。 绑定(...)。 由于 bind(...) 返回 true,因此 result 设置为 true

每当你说

result = result || bind(...)  // result is true at this point

...bind(...)表达式不会被计算,因为它返回什么并不重要; 表达式 true || Anything 始终为 true,并且 || 表达式 短路

确保始终调用 bind 的一种方法是将其移动到 || 的左侧,或者将 || 更改为&&,具体取决于您想要通过 result 实现的目标。

The || expression short circuits after the first time bind returns true.

The first time you evaluate

result = result || bind(...)  // result is false at this point

bind is called, because that's the only way to determine the value of false || bind(...). Because bind(...) returns true, result is set to true.

Every other time you say

result = result || bind(...)  // result is true at this point

... the bind(...) expression isn't evaluated, because it doesn't matter what it returns; the expression true || anything is always true, 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 with result.

娇纵 2024-07-22 12:33:35

在您的特定示例中,Boost.Lambda 并没有真正为您带来任何好处。 去掉 lambda 部分,也许你会更清楚地看到发生了什么:

for (int i = 0; i < 10; ++i)
  result = result || callback();

这仍然依赖于你知道 || 运算符是短路的,如 丹尼尔解释了

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:

for (int i = 0; i < 10; ++i)
  result = result || callback();

This still relies on you to know that the || operator is short-circuited, as Daniel explained.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文