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;


No Trackbacks


Display comments as Linear | Threaded

Sir Milten on :

Nice! Good to know!

monster review on :

In the programming language one of the top and basic language which is used in C++ so that you will need to know the whole info. Variadic template with the in compiling your code in a very easy way.

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