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

标签 c++ parameter-passing c++17 ellipsis variadic

有没有什么办法可以让这段代码按预期编译和工作,而无需诉诸 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 风格的参数包扩展。

编号:it's the same as

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/

相关文章:

c++ - 命名空间菜鸟问题 : two cpp files sharing the same namespace have the same variable

php - 将数据从 php 传递到 javascript 的最有效方式 - 隐藏表单字段或 json_encode

c++ - c++17如何获取 "any"存储的数据大小?

c++ - 你能专攻 std::unique_lock 吗

c++ - 我需要什么类型的类(class)?

c++ - 从多个线程同步对共享对象的方法调用

c++ - 同一文件流中的 fread 和 fgetc 不起作用

PowerShell 函数参数

java - 在 Java 中,有时方法参数的行为类似于通过引用传递,尽管事实并非如此。他们通过什么方法?

c++ - 将 std::invoke_result_t 与通用 lambda 一起使用时出现硬错误