lightxbulb
lightxbulb

Reputation: 1321

Evaluating a parameter pack

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?

Upvotes: 1

Views: 101

Answers (1)

Oliv
Oliv

Reputation: 18051

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";});
}

Upvotes: 7

Related Questions