Passing parameters dynamically to variadic functions

前端 未结 4 1866
余生分开走
余生分开走 2020-11-30 13:02

I was wondering if there was any way to pass parameters dynamically to variadic functions. i.e. If I have a function

int some_function (int a, int b, ...){/*         


        
4条回答
  •  借酒劲吻你
    2020-11-30 13:41

    Depending on what it is you're passing around, it could be a discriminated union you're after here (as hinted at in the comments). That would avoid the need for variadic functions or arrays of void*, and answers the question "how does some_function know what you actually passed it". You might have code something like this:

    enum thing_code { INTEGER, DOUBLE, LONG };
    
    struct thing
    {
     enum thing_code code;
     union
     {
        int a;
        double b;
        long c;
     };
    };
    
    void some_function(size_t n_things, struct thing *things)
    {
        /* ... for each thing ... */
        switch(things[i].code)
        {
          case INTEGER:
          /* ... */
        }
    }
    

    You can take this a step further and avoid the switch by replacing the code with one or more pointers to functions that do something useful with each thing. For example, if what you wanted to do was to simply print out each thing, you could have this:

    struct thing
    {
     void (*print)(struct thing*);
     union
     {
       ...
     };
    }
    
    void some_function(size_t n_things, struct thing *things)
    {
      /* .. for each thing .. */
      things[i]->print(things[i]);
      /* ... */
    }
    

提交回复
热议问题