c++ - 如何调用使用数组将函数应用于可变参数包的成语

标签 c++ c++11 variadic-templates idioms

这里是有问题的习语:

template<typename... T>
void f(T... t) {
    int temp[] = {(g(t), 0)...};
}

这将被编译为 g(t0); g(t1); ...,函数调用的顺序由 C++11[dcl.init.list]/4 保证。
更好的版本使用 std::initializer_list 而不是数组,但这在这里并不重要。

问题是:我们应该如何称呼这个成语?

更新:
基本上,这是我们应该建议人们使用它而不是递归的成语,即替换两个重载
void f() {}
void f(H head, T... tail) { g(head); f(尾...); }
单例
void f(T... t) { int temp[]{(g(t), 0)...};

当然我们可以称它为“将被Fold Expressions取代的成语”,但我希望它有一个合适的称呼。

最佳答案

包扩展。

[expr.prim.lambda] 中的 C++11 §5.1.2/23:

A capture followed by an ellipsis is a pack expansion (14.5.3). [Example:

template<class... Args>
void f(Args... args) {
  auto lm = [&, args...] { return g(args...); };
  lm();
}

—end example ]

我认为这涵盖了它。不应用函数的包展开可以看作是应用恒等函数。

[temp.variadic] 中的 C++11 §14.5.3/4:

A pack expansion consists of a pattern and an ellipsis, the instantiation of which produces zero or more instantiations of the pattern in a list (described below). […]

关于c++ - 如何调用使用数组将函数应用于可变参数包的成语,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28887549/

相关文章:

C++:如何将模板数组声明为函数参数

c++ - 在这种情况下,模板参数推导如何工作?

c++ - 出现在可变模板参数包的任何位置的类型的类模板的部分特化

c++ - 我的 RSA 实现有什么问题

C++ 虚拟方法,不需要 "this"指针 - 优化

c++ - 使用 std::fill 填充多维数组的安全方法是什么?

c++ - 区分 const char[N] 和 std::string 的类型特征?

c++ - 如何为模板类型创建别名?

c++ - std::vector 在不知道元素类型的情况下插入

c++ - 将 1D 转换为 2D?