Variadic Template is introduced in C++11. Variadic Template allows a function to take variable number of arguments of any type.

Let’s understand by an example.

Suppose we want to create a function log() that accepts variable number of arguments of any type and prints them on console i.e.

It means we have 2 requirements while creating log() function i.e.

1.) It should accept any type of arguments.
2.) It should accept variable number of arguments.

Now as per requirement 1, argument can be of any type. So its clear the we need to create a template function, something like this,

But this function accepts only one argument. To full fill 2nd requirement we need to create a function that accepts,  variable number of template parameters. This feature is Variadic Template.

Vardiac Template Function: Creating function that accepts variable number of arguments of ant type

With vardiac template we can define a function that accepts variable number of template parameters i.e.

The above function can take 1 or more arguments. Here, Args… represents variable number of template parameters.

Declaring a vardiac template function is easy but its definition is little tricky. We cann’t access the the passed variable number of arguments directly. We need to use the c++ type deduction mechanism & recursion to achieve this. Let’s define the variadic function i.e.

 

Let’s see how it works. Suppose we called the log() function i.e.

As we have passed 3 arguments of int, double & const char * type. So, using template type deduction mechanism, compiler will internally create following function out of the given variadic template function i.e.

It will print the first parameter and forward other 2 parameters to another log function. Now using template type deduction mechanism,  compiler will internally create following function out of the given variadic template function i.e.

It will print the first parameter and forward other 1 parameters to another log function. Now using template type deduction mechanism, compiler will internally create following function out of the given variadic function i.e.

It will print the first parameter and as no other argument is received, it will call the log() function with no parameter i.e. then returns back. That’s why we defined a log() function with no parameter.

So, this will be stack trace of calling above variadic template function is as follows,

Complete Example is as follows,

Output