有没有办法让这段代码在不求助于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;
}发布于 2018-05-12 17:46:04
我怀疑你误解了签名的意思。
void fct (int index, int indexes...)我怀疑您认为fct()需要一个int single value (index)和一个int (indexex...)变量列表以及C++11风格的参数包扩展。
否:it's the same as
void fct (int index, int indexes, ...)所以两个 int单值和一个C风格的可选参数,你只能通过va_list来使用。
如果您不相信这一点,请尝试仅使用整数参数调用fct()
fct(1);对于fct()的可变版本,您应该会得到一个" error : no matching function for call to 'fct'“类型的错误,以及一条”注意:候选函数不可行:需要至少2个参数,但提供了1个参数“的注释。
如果你想接收一个可变的参数列表并递归地传递给同一个函数,你可以使用模板可变的方式。
举例说明
template <typename ... Ts>
void fct(int index, Ts ... indexes)
{
std::cout << index << ' ';
fct(indexes...);
}发布于 2018-05-12 19:16:33
如果你真的不喜欢模板的想法,我想你可以像这样欺骗一下:
#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;
}https://stackoverflow.com/questions/50302939
复制相似问题