Search code examples
c++templatesc++17variadic-templatesfold-expression

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?


Solution

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