Variadic Function templates in C++ allow you to write flexible functions that can accept any number of arguments, regardless of their types. This is particularly useful for creating functions like custom print functions, aggregators, or any function that needs to handle a list of varying types of arguments. Variadic templates utilize a special syntax with ellipsis (…) to handle an arbitrary number of template arguments.
Below is a simple C++ program demonstrating the use of variadic function templates. We’ll write two examples:
1. A print function that can accept and print any number of arguments.
2. A sum function that can add up any number of integer arguments.
Example 1: Print Function
This function will print each argument followed by a space.
#include <iostream>
// Base function needed to end the recursion
void print() {
std::cout << std::endl; // End the line at the end of output
}
// Template variadic function to print any number of arguments
template<typename T, typename… Args>
void print(const T& firstArg, const Args&… args) {
std::cout << firstArg << ” “; // Print the first argument
print(args…); // Recursive call with the rest of the arguments
}
int main() {
print(1, 2.5, “hello”, ‘a’);
return 0;
}
Example 2: Sum Function
This function will add up any number of integer arguments. This demonstrates using recursion in variadic templates to compute a result.
#include <iostream>
// Base function to end the recursion and return the last element
int sum() {
return 0; // Return 0 when there are no elements left
}
// Template variadic function to sum any number of integers
template<typename… Args>
int sum(int firstArg, Args… args) {
return firstArg + sum(args…); // Recursive call to sum the rest of the arguments
}
int main() {
std::cout << “Sum of 1, 2, 3, 4 is ” << sum(1, 2, 3, 4) << std::endl;
return 0;
}
How Variadic Templates Work
- Print Function
The print function is a template that takes a first argument of any type and then uses a parameter pack (Args…) for the rest of the arguments.
- It prints the first argument, then recursively calls itself with the remainder of the arguments (args…).
- The recursion ends when it hits the base print() function that just prints a newline.
2. Sum Function
Similar to print, the sum function uses a template to handle an initial integer and a parameter pack for the rest.
- It recursively sums each integer by adding the first argument to the result of a recursive call.
- The base case here is a sum() function that returns 0, which handles the scenario when the parameter pack is empty.