Variadic function templates in C++ with example

In this tutorial, we will learn what are variadic function templates, its syntax and how to implement it using an example in C++.

Variadic function templates in C++

Templates that can accept a variable number of arguments are called variadic templates i.e., they can accept any number of arguments. When these templates are applied on functions these are called variadic function templates.

Declaring variadic templates:
template <class… t1>

This type of template allows zero or more arguments. For a template to only allow a positive number of arguments we need to declare it as follows:
template <class t1, class… t2>

We generally implement the variadic templates recursively. There isn’t any easy implementation technique to iterate over the values of the variadic template.

Example of Variadic function templates

#include <iostream> 
using namespace std; 

void my_fun() 
{ 
  cout << "Printing is completed." << endl;
}

// Variadic function template
template <class t1, class... t2>
void my_fun(t1 v1,t2... v2) 
{ 
  cout << v1 << endl; 
  my_fun(v2...); 
} 

int main() 
{ 
  my_fun (5, "Codespeedy", 9.55, "Hello");
  my_fun ("Meghana", 99);
  return 0; 
} 

In this example, we implemented the variadic function template along with the concept of function overloading and recursion.

In main, we first called the function ‘my_fun’ with 4 arguments.  This calls the variadic function and v1 contains the value 5 and v2 contains all the remaining values(“Codespeedy”, 9.55, “Hello”). We are printing the value in v1 and calling ‘my_fun’ recursively on v2. For the last recursive call which contains no arguments, the overloaded ‘my_fun’ will be called.

We observe that every time the variadic function can accept a variable number of arguments. This is the use of variadic function templates in C++.

Output:

5
Codespeedy
9.55
Hello
Printing is completed.
Meghana
99
Printing is completed.

You may also read,
Template Parameters and Template Arguments in C++
Function Overloading in C++

Leave a Reply

Your email address will not be published. Required fields are marked *