有没有什么办法可以让这段代码按预期编译和工作,而无需诉诸 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);
你应该得到一个类型为“error: no matching function for call to 'fct'”的错误和一个类型为“note: candidate function not viable: requires at least 2 arguments, but 1 was provided”的关于可变参数的错误fct()
的版本。
如果你想接收可变参数列表并递归传递给同一个函数,你可以使用模板可变参数方式。
举例
template <typename ... Ts>
void fct(int index, Ts ... indexes)
{
std::cout << index << ' ';
fct(indexes...);
}
关于c++ - 将参数传递给另一个可变参数函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50302939/