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

大城市里の小女人 提交于 2019-12-06 05:20:48

问题


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!


回答1:


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)



回答2:


Just pass args as a parameter of type va_list to func2




回答3:


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.



来源:https://stackoverflow.com/questions/3672753/how-to-pass-variable-number-of-arguments-from-one-function-to-another

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