评估参数包

lig*_*ulb 1 c++ templates variadic-templates fold-expression c++17

这是不使用折叠来评估参数包的唯一方法(因为它需要使用运算符)吗?

#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";});
}
Run Code Online (Sandbox Code Playgroud)

本质上,我想这样做(f(Is)...),但是由于某些原因,这在C ++中是不允许的。是否有比使用上述解决方法更优雅的方法?

Oli*_*liv 7

有一个更简单的解决方案:

#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";});
}
Run Code Online (Sandbox Code Playgroud)

  • @lightxbulb:发射它们:)`((void)f(Is),...)`可以防止过载,或类似的事情。 (4认同)