c++ - 将可变参数函数模板的每个参数传递给返回 void 的函数

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

根据找到的食谱here ,我写了以下内容:

void printInt(int a) {std::cout << a << std::endl;}

template <typename... Args>
void f(const Args &... args) {
    auto temp = {(printInt(args), void(), 0)...};
    auto a = temp; temp = a;
}

两个问题:

  1. 以下语法是什么意思:{(printInt(args), void(), 0)...}

  2. 我添加了行 auto a = temp; temp = a; 以免收到有关未使用变量 temp 的警告。有没有更好的办法?


在回复和评论中的解释之后,唯一剩下的问题是:为什么 C++ 不允许这样做:

template <typename... Args>
void f(const Args &... args) {
    printInt(args)...;
} 

在引用的帖子中提出了这个问题,但没有得到任何答复。

最佳答案

  1. 这个语法意味着temp将是 std::initializer_list<int>由于逗号运算符规则,用零填充(将计算所有表达式,但只使用最后一个,因此,将为每个参数调用函数 printInt,并将 0 放入每个参数的初始化列表中)。

N4296 5.19/1

A pair of expressions separated by a comma is evaluated left-to-right; the left expression is a discarded- value expression (Clause 5). 87 Every value computation and side effect associated with the left expression is sequenced before every value computation and side effect associated with the right expression. The type and value of the result are the type and value of the right operand; the result is of the same value category as its right operand, and is a bit-field if its right operand is a glvalue and a bit-field. If the value of the right operand is a temporary (12.2), the result is that temporary.

{(printInt(args), void(), 0)...};

()用于包扩展,因此,...将应用于完整表达式,void()在这里是为了保护构造免受类重载运算符的影响,(感谢 Quentin),您还可以使用以下

{((void)printInt(args), 0)...};

还有,用起来会更好

{0, ((void)printInt(args), 0)...};

对于 initializer_list 中的至少一个元素(因此您可以不带参数调用 f)。

  1. 您可以使用 (void)temp;标记变量未使用,这里有更多信息:What does (void) 'variable name' do at the beginning of a C function?

关于c++ - 将可变参数函数模板的每个参数传递给返回 void 的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31743403/

相关文章:

c++ - 使用boost shared_ptr时使用默认参数

c++ - 根据模板参数启用模板 Ctor

c++ - 推导引用模板参数的类型

c++ - 使用 gcc 在 Linux 上运行线程构建 block (Intel TBB)

c++ - 在函数模板中打包扩展调用模板化方法

c++ - 编写此类程序的最佳方法 "writing the code "::Qt

c++ - 在 Windows Mobile 设备上,显示“确定”按钮而不是“X”按钮的最佳方式是什么?

c++ - 模板函数依赖于非类型参数

c++ - 将函数模板传递给其他函数

c++ - 动态分配的字符串数组未能解除分配