首页 > 解决方案 > 将参数传递给另一个可变参数函数

问题描述

有没有办法让这段代码按预期编译和工作而无需求助于任何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;
}

标签: c++parameter-passingc++17ellipsisvariadic

解决方案


我怀疑你误解了签名的含义

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

我怀疑您认为fct()期望int单个值 ( ) 和具有 C++11 样式的参数包扩展的's ( )index的可变参数列表。intindexex...

否:

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...);
}

推荐阅读