c++: pass arbitrary number of arguments to another function

时间秒杀一切 提交于 2021-02-11 05:04:51

问题


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.

Thanks


回答1:


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



回答2:


There is no way that you can efficiently move arguments of a variadic function to another function, but you can move your stack to another function, so it can peek arguments from stack itself. Ansi C introduce va_list just for this purpose. You can have following code:

void fwd_function( int argCount, ... ) {
    va_list vargs;
    va_start( vargs, argCount );
    impl_function( argCount, vargs );
    va_end( vargs );
}
void impl_function( int argCount, va_list args ) {
    int i;
    for( i = 0; i < argCount; i++ ) {
        int arg = va_arg( args, int );
    }
}



回答3:


You should use a variadic templates and perfect forwarding in C++11.

If you don't have that, AFAIK there's a Boost library that will mimick those for you.



来源:https://stackoverflow.com/questions/12712212/c-pass-arbitrary-number-of-arguments-to-another-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!