CPP11 – Variadic Template Function | Tutorial & Examples

In the previous article, we have discussed about C++11 – std::all_of() – Algorithm tutorial and example. Let us learn how to Variadic Template Function in C++ Program.

Variadic Template Function

Variadic templates are functions that take variable number of arguments. These were introduced in C++11.

The major requirements are that the function should take variable number of arguments and it can be of any type.

We can achieve the second requirement easily by using template. For the other one we would need something that can take multiple arguments. Here the variadic template can be used.

Let’s Create function that accepts variable number of arguments of any type :

We can easily declare a vardiac template function however the definition is complicated. To access the passed variable we have to use the recursion with the deduction mechanism of c++.

#include <iostream>
// Function without any parameters
// used to break the parameter
void examplePrint()
{
}
/*
 * Variadic Template Function which
 *will accept any type and number of arguments
 *and print it.
 */
template <typename T, typename... Args>
void examplePrint(T elem1, Args... args)
{
    // Prints the elem1 element from the arguments
    std::cout << elem1 << " , ";
    // Using recursion to pass the remaining arguments
    examplePrint(args...);
}
int main()
{
    examplePrint('a', 123, 3.14, "Hi");
    return 0;
}
Output :
a , 123 , 3.14 , Hi ,