lundi 24 juin 2019

How do I implement a variadic pattern to forward variable number of arguments to a function in C++11?

In python, I am able to use *args to allow a variable number of inputs into a function. For example, the following snippet will print out all arguments passed when f is called:

def f(*args):
  for a in args:
    print(a)

I would like to be able to implement a pattern like this in C++11 with the following requirements:

The function f will always take in a value of a certain type T and then a variable number of inputs after; this includes, potentially, 0 additional inputs.

The additional inputs are not necessarily of the same type, so using an initializer list won't work.

The function f will be called by another function g which will need to forward the optional arguments to f:

T g(const T& x, args...) {
  T output = f(x, args...);
  return output;
};

T f(const T& x, args...) {
  // do some stuff and return an object of type T
};

How can I solve this design problem? I have tried variadic templates but I can't seem to make my implementation work correctly (compiles but doesn't link because of rvalue reference issues).

Aucun commentaire:

Enregistrer un commentaire