Skip to content

Variadic templates with initializer lists

C++11 introduced variadic templates that can be used to define functions that take an arbitrary number of arguments like printf(). For example, here is a definition of a simple add function via a recursive template:


template <typename T>
T add(T arg) {
  return arg;
}

template <typename T, typename... Ts>
T add(T arg, Ts... args) {
  return arg + add(args...);
}
 

Another way to define the above add() function is via initializer lists without any recursion.


template <typename T, typename... Ts>
T add(T arg, Ts... args) {
  auto sum = arg;
  T values[] = {args...};
  for (auto v : values) {
      sum += v;
  }
  return sum;
}