1

Is this the only way to evaluate a parameter pack without using folding (since it requires the use of operators)?

#include <iostream>

template<int ...Is, typename Function>
void eval(Function&& f)
{
    // (f(Is)...);
    auto op = [&f](int i){f(i); return 0;};
    auto doNothing = [](auto...){};
    doNothing(op(Is)...);
}

int main()
{
    eval<0,1,2>([](int x){std::cout << x << "\n";});
}

Essentially I want to do (f(Is)...), but for some reason, this is disallowed in C++. Is there a more elegant way this can be achieved than by using the workaround presented above?

max66
  • 65,235
  • 10
  • 71
  • 111
lightxbulb
  • 1,251
  • 12
  • 29
  • 1
    @user7769147 that's not true, this is just fine. – Pezo Oct 20 '19 at 18:11
  • 1
    never underestimate the power of the comma operator – max66 Oct 20 '19 at 18:15
  • 3
    You just need a coma between `f(Is)` and `...`. `(f(Is)...)` is a parameter pack expansion that can appear as a function argument. `(f(Is),...)` is a fold expression on the comma operator. – Oliv Oct 20 '19 at 18:15
  • 1
    `since it requires the use of operators`: coma is an operator! – ph3rin Oct 20 '19 at 18:18

1 Answers1

7

There is a simpler solution:

#include <iostream>

template<int ...Is, typename Function>
void eval(Function&& f)
{
    (f(Is),...);
}

int main()
{
    eval<0,1,2>([](int x){std::cout << x << "\n";});
}
Oliv
  • 17,610
  • 1
  • 29
  • 72