2

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).

JeJo
  • 30,635
  • 6
  • 49
  • 88
joe.dinius
  • 376
  • 1
  • 10

1 Answers1

5

Here's how you'd write this in C++:

template <class... A>
T f(const T &x, A &&... arg)
{
  // do some stuff and return an object of type T
}

template <class... A>
T g(const T &x, A &&... arg)
{
  T output = f(x, std::forward<A>(arg)...);
  return output;
}

Note that since templates are involved, the code must be in a header file to prevent linking issues.

Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455