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

### Comments

Display comments as Linear | Threaded

#### Sir Milten on Friday, April 7. 2017:

Nice! Good to know!

#### monster review on Sunday, April 19. 2020:

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.