将参数传递给另一个可变函数 [英] Passing arguments to another variadic function

查看:98
本文介绍了将参数传递给另一个可变函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码是否有任何方式可以按预期方式编译和工作而无需使用 va_list 东西?

Is there any way at all for this code to compile and work as intended without resorting to va_list stuff ?

#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;
}


推荐答案

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

I suspect you have misunderstood the meaning of the signature

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

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

I suspect you think that fct() expect a int single value (index) and a variadic list of int's (indexex...) with C++11 style of parameter pack expansion.

否:

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

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

so two int single values and a C-style of optional argument that you can use only through va_list stuff.

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

If you don't believe it, try calling fct() with only an integer argument

fct(1);

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

You should obtain an error of type "error: no matching function for call to 'fct'" with a note of type "note: candidate function not viable: requires at least 2 arguments, but 1 was provided" regarding the variadic version of fct().

如果要接收可变参数列表并将其递归传递给相同的函数,则可以使用可变参数模板。

If you want receive a variadic list of parameters and recursively pass the to the same function, you can use the template variadic way.

例如

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

这篇关于将参数传递给另一个可变函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆