How to Create a Function Template in C++?
In C++, templates enable us to write generic programs that handle any data type. We can create a template class, function, and variable. A template function is a function that can work with any data type. In this article, we will learn how to create a function template in C++.
Create a Function Template in C++
To create a template function in C++, we use the template keyword followed by the typename keyword (or class keyword) and a placeholder for the type.
Syntax of Function Template
template<typename T> returnType functionName(T parameter1, T parameter2, ...) { // Body of the function }
where:
- template: This keyword can be used to declare the template
- <typename T>: It can be used to declare the template parameter T.
- returnType: This can be used to specify the return type.
- T parameter1, T parameter: These are function parameters of type T.
C++ Program to Create a Function Template
C++
// C++ Program to illustrate how to Create a Template // Function #include <iostream> using namespace std; template < typename T> T max_value(T a, T b) { return (a > b) ? a : b; } // Driver Code int main() { // Example usage of the max template function with // different data types cout << "Max of 5 and 10: " << max_value(5, 10) << endl; cout << "Max of 3.5 and 7.2: " << max_value(3.5, 7.2) << endl; return 0; } |
Output
Max of 5 and 10: 10 Max of 3.5 and 7.2: 7.2