Boost Lambda Perplexity

Why is the callback called only once?

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;
}
+3
source share
2 answers

short circuit bind returns a short circuit|| expression .

One way to ensure that it is bindalways called is to move it to the left side ||or change ||to &&, depending on what you are trying to do with result.

+8
source

In your specific example, Boost.Lambda doesn't actually give you anything. Get rid of the lambda parts and you might see what happens next:

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

, , || , .

+1

Source: https://habr.com/ru/post/1705061/


All Articles