
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Variadic function templates in C++
What is Variadic Function
In mathematics and in computer programming, a variadic function is a function of indefinite arity, i.e., a function that accepts a variable number of arguments. So, In C++ programming, we can say that a function that accepts a variable number of arguments is variadic function.
Why Variadic Function Templates Are Used?
In C++, templates can only have a fixed number of parameters, which must be specified at the time of declaration. However, variadic templates can help to solve this issue.
Syntax to Create Variadic Function
Following is the variadic function template syntax:
template<typename arg, typename... args> return_type function_name(arg var1, args... var2)
Example of Variadic Function Templates
In the following example, we are showcasing how we can use the variadic function template in C++:
#include <iostream> using namespace std; void print() { cout << "I am not using vriadic so, I called at last.\n"; } template < typename T, typename...Types > void print(T var1, Types...var2) { cout << var1 << endl; print(var2...); } // Driver code int main() { print(1, 2, 3.14, "Pass me any " "number of arguments", "I will print\n"); return 0; }
Following is the output of the above code:
1 2 3.14 Pass me any number of arguments I will print I am not using vriadic so, I called at last.
Example: Variadic Template Print Function
Following is another C++ example of the variadic function template:
#include <iostream> using namespace std; void print() { cout << "End of recursion!" << std::endl; } // Variadic template function template < typename T, typename...Args > void print(T first, Args...rest) { cout << first << " "; print(rest...); } int main() { print(1, 2.5, "Hello", 'A'); return 0; }
Following is the output:
1 2.5 Hello A End of recursion!
Advertisements