c++ - 将参数传递给另一个可变参数函数
问题描述
有没有办法让这段代码按预期编译和工作而无需求助于任何va_list
东西?
#include <iostream>
void fct(void)
{
std::cout << std::endl;
}
void fct(int index, int indexes...)
{
std::cout << index << ' ';
fct(indexes); //or fct(indexes...); ?
}
int main(void)
{
fct(1, 2, 3, 4, 5, 6, 7);
return 0;
}
解决方案
我怀疑你误解了签名的含义
void fct (int index, int indexes...)
我怀疑您认为fct()
期望int
单个值 ( ) 和具有 C++11 样式的参数包扩展的's ( )index
的可变参数列表。int
indexex...
否:与
void fct (int index, int indexes, ...)
所以两个 int
单一值和一个 C 风格的可选参数,你只能通过va_list
东西使用。
如果您不相信,请尝试fct()
仅使用整数参数调用
fct(1);
你应该得到一个类型为“error: no matching function for call to 'fct'”的错误,并附上关于fct()
.
如果你想接收一个可变参数列表并递归地传递给同一个函数,你可以使用模板可变参数的方式。
举例
template <typename ... Ts>
void fct(int index, Ts ... indexes)
{
std::cout << index << ' ';
fct(indexes...);
}
推荐阅读
- python - tqdm 在较大循环内具有间隔
- mongodb - 使用 MongoDB Go 驱动程序,如何设置连接池?
- laravel - 使用laravel 5.6登录时如何发送随机生成的数字以及电子邮件和密码
- d3.js - 为什么拖动回调中的 d3.event 与数据坐标有关
- php - 防止某人在上传表单和图像时刷新页面?
- android - 一些库更新后,Android 平台构建失败
- sass - 容器流体仅适用于台式机,仅适用于 lg 设备
- python - 加载库失败:cairo
- python - Pycharm 无法检测 django 频道
- elasticsearch - Elastic Search 如何选择列并通过过滤器?