将参数传递给另一个可变参数函数

Passing arguments to another variadic function

本文关键字:变参 参数 函数 另一个 参数传递      更新时间:2023-10-16

有没有办法让这段代码在不诉诸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的单值(index(和一个int的可变参数列表(indexex...(,C++11风格的参数包扩展。

否:与

void fct (int index, int indexes, ...)

所以两个int单个值和一个 C 样式的可选参数,您只能通过va_list的东西使用。

如果您不相信,请尝试仅使用整数参数调用fct()

fct(1);

您应该获得类型为"错误:调用'fct'没有匹配函数"的错误,并带有"注意:候选函数不可行:至少需要 2 个参数,但提供了 1 个参数"类型的注释,关于fct()的可变参数版本。

如果你想接收参数的可变参数列表并递归传递给同一个函数,你可以使用模板可变参数的方式。

通过示例

template <typename ... Ts>
void fct(int index, Ts ... indexes)
{
std::cout << index << ' ';
fct(indexes...);
}

如果你真的不喜欢模板的想法,我想你可以像这样作弊:

#include <iostream>
#include <vector>
void fct(std::vector<int>&& _indices)
{
for (auto&& i : _indices)
{
std::cout << i << ' ';
}
std::cout << std::endl;
}
int main(void)
{
fct({1, 2, 3, 4, 5, 6, 7}); // Note the curly braces
return 0;
}