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;
}
 

Trackbacks

No Trackbacks

Comments

Display comments as Linear | Threaded

Sir Milten on :

Nice! Good to know!

Add Comment

Standard emoticons like :-) and ;-) are converted to images.
You can use [geshi lang=lang_name [,ln={y|n}]][/geshi] tags to embed source code snippets.
Markdown format allowed
Form options