views:

97

answers:

3

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

I'd like to achieve 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 is going to be duplicated multiple times so I'd like to keep it as minimalist as possible while also keeping the function call very short

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

Thanks!

+2  A: 

Just pass args as a parameter of type va_list to func2

Brian R. Bondy
+3  A: 

No, you have to pass the varargs using a va_list as per your second example.

It's just 3 lines extra code, if you want to avoid duplicating those lines, and func2 is always the same, or atleast takes the same parameters, make a macro out of 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)
nos
I'm using macros right now but I was hoping there was a better way. Thanks
Zain
@Zain: what problem are you experiencing that a better way might improve on? Or is just a general concern about evil macros and identifier clashes?
Tony
A: 

Maybe you could try wrapping the parameters in a struct.

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 sometime use that trick when the list of parameter changes a lot during refactoring.

I'm not sure from your question if that could solve your problem though.

--

It is interesting to note that the same thing can be used for templates by defining typedefs and the like in the struct (i usually always use class in my code, since there is basically no difference between struct and class in c++) instead of normal members. It can be a workaround to the problem of having to maintain code with lot of templates that will change a lot during refactoring or developement.

n1ck