C++:将任意数量的参数传递给另一个函数 [英] c++: pass arbitrary number of arguments to another function

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

问题描述

我有一个接受 3 个参数的函数.其他函数的向量、void* 和任意参数列表.该函数旨在将其 void* 和任意参数列表传递给列表中的每个函数,函数将自行处理这些参数.这是我想要的一个例子:

I have a function that takes 3 arguments. a vector of other functions, a void*, and an arbitrary list of arguments. The function is designed to pass in it's void* and arbitrary list of arguments to each function in the list, which the functions will handle themselves. here is an example of what I want:

typedef void (*fptr)(const void* userdata, ...);

void execute_all(vector<fptr> funcs, void* userdata, ...){
    for (int i = 0;i<funcs.size();i++){
        fptr func = funcs[i];
        //execute func with userdata and ... from above.
        //like (*func)(userdata, ...); which obviously doesnt work
    }
}

我需要知道如何将所有参数转发到每个函数中.不要担心确保兼容性.我在别处处理.

I need to know how to forward all arguments into each function. Dont worry about ensuring compatibility. I handle that elsewhere.

谢谢

推荐答案

您不能直接将可变参数从可变参数函数传递到另一个可变参数函数.但是,您可以让被调用的(内部)函数接受 va_list,然后传递该列表:

You can't directly pass down variadic arguments from a variadic function to another variadic function. However, you can make the called (inner) function accept a va_list, then pass that list around:

#include <cstdarg>

void callee(void *first, va_list args);

void caller(void *first, ...)
{
    va_list args;
    va_start(args, first);
    callee(first, args);
    va_end(args);
}

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

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