How to pass a variable number of arguments from one function to another?

Is there a way to directly pass a variable number of arguments from one function to another?

I would like to get a minimal solution like the following:

int func1(string param1, ...){ int status = STATUS_1; func2(status, param1, ...); } 

I know I can do this using something like the following, but this code will be duplicated several times, so I would like to keep it as minimal as possible, as well as a very short circuit of the function

 int func1(string param1, ...){ int status = STATUS_1; va_list args; va_start(args, param1); func2(status, param1, args); va_end(args); } 

Thanks!

+4
source share
3 answers

No, you need to pass varargs using va_list according to your second example.

These are just 3 lines of additional code, if you want to avoid duplication of these lines, and func2 is always the same, or at least takes the same parameters, it produces a macro from it.

 #define CALL_MY_VA_FUNC(func,param) do {\ va_list args; \ va_start(args,param);\ func(param,param,args);\ va_end(args); } while(0) 
+6
source

Just pass args as a parameter of type va_list to func2

+3
source

Perhaps you could try wrapping the parameters in a structure.

 struct Params { int status; std::string param1; }; void func1(Params& params) { int status = params.status; func2(params); } void func2(Params& params) { std::string param1 = params.param1; } 

I ever use this trick when the parameter list changes a lot during refactoring.

I am not sure about your question whether this can solve your problem.

-

It is interesting to note that the same can be used for templates, defining typedefs, etc. in the structure (usually I always use a class in my code, since in principle there is no difference between struct and class in C ++) of normal members. This can be a workaround to the problem of having to maintain code with many templates that will change a lot during refactoring or development.

0
source

All Articles