Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 596
Patrick Kwok Avatar asked Aug 09 '26 21:08

Patrick Kwok


1 Answers

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';
}
like image 158
JHBonarius Avatar answered Aug 12 '26 11:08

JHBonarius



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!