3

I have functions foo, bar, baz defined as follows:

template <typename ...T>
int foo(T... t)
{
   return (bar(t), ...);
}

template <typename T>
int bar(T t)
{
    // do something and return an int
}

bool baz(int i)
{
    // do something and return a bool
}

I want my function foo to stop folding when baz(bar(t)) == true and return the value of bar(t) when that happens. How can I modify the above code to be able to do that?

cigien
  • 57,834
  • 11
  • 73
  • 112
locke14
  • 1,335
  • 3
  • 15
  • 36

1 Answers1

7

Use short circuit operator && (or operator ||):

template <typename ...Ts>
int foo(Ts... t)
{
    int res = 0;
    ((res = bar(t), !baz(res)) && ...);
    // ((res = bar(t), baz(res)) || ...);
    return res;
}

Demo

Note:
(baz(res = bar(t)) || ...); would even be shorter, but less clear IMO.

Jarod42
  • 203,559
  • 14
  • 181
  • 302