Search code examples
c++variable-assignmentvariadic

How to assign variadic/variable arguments in C++


I'm trying to create a function to assign default or input values to several (scalar) parameters using variadic/variable input arguments as:

void set_params(const vector<double> &input, int n, ...) {  
  va_list args;
  va_start (args, n);
  for (int i = 0; i < n; i++) {
    if (i < input.size()) {
      va_arg(args, int) = input[i];
    }
  }
  va_end(args);
}

int a = 1, b = 2, c = 3;
set_params({10, 20}, 3, a, b, c);

However, I'm getting the error on the assignment va_arg(args, int) = input[i]. Is it possible somehow to do assignment with variable arguments, or is there a better way to achieve this?


Solution

  • Instead of using C's va_ stuff, C++ has it's own variadic template arguments, which you should preferably use

    I'm no expert on this, but it could look a little bit like

    #include <vector>
    #include <iostream>
    
    template <typename... Arg>
    void set_params(const std::vector<double> &input, Arg&... arg) {
        unsigned int i{0};
        (
            [&] {
                if (i < size(input)) {
                    arg = input[i++];
                }
            }(), // immediately invoked lambda/closure object
            ...); // C++17 fold expression
    }
    
    int main() {
        int a = 1, b = 2, c = 3;
        set_params({10, 20}, a, b, c);
    
        std::cout
            << a << ' '
            << b << ' '
            << c << '\n';
    }