【问题标题】:Evaluating a parameter pack评估参数包
【发布时间】:2019-10-20 18:05:20
【问题描述】:

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

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

基本上我想做(f(Is)...),但由于某种原因,这在 C++ 中是不允许的。有没有比使用上述解决方法更优雅的方法来实现这一点?

【问题讨论】:

  • @user7769147 这不是真的,这很好。
  • 永远不要低估逗号运算符的威力
  • 您只需要在f(Is)... 之间加一个逗号。 (f(Is)...) 是一个参数包扩展,可以作为函数参数出现。 (f(Is),...) 是逗号运算符的折叠表达式。
  • since it requires the use of operators: coma 是运算符!

标签: c++ templates c++17 variadic-templates fold-expression


【解决方案1】:

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

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

【讨论】:

  • 如果有人超载, 会发生什么?
  • @lightxbulb:你解雇他们 :) ((void)f(Is),...) 可能会防止过载,或类似的事情。
猜你喜欢
  • 2015-12-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多