Using the template we can create a generic function that will perform the set of operations on different data types. The type of data that the function will operate upon is passed to it as a parameter. Let see an example code,
In the below code, I am creating a generic function using the template that will find the smallest number among two passed numbers.
#include <iostream>
using namespace std;
template <typename T>
T findMinNumber(T x, T y)
{
return (x < y)? x: y;
}
int main()
{
cout << findMinNumber<int>(2, 7) << endl; // Call findMinNumber for int
cout << findMinNumber<double>(3.5, 7.0) << endl; // call findMinNumber for double
cout << findMinNumber<char>('d', 'p') << endl; // call findMinNumber for char
return 0;
}
Using the template we can create a generic function that will perform the set of operations on different data types. The type of data that the function will operate upon is passed to it as a parameter. Let see an example code,
In the below code, I am creating a generic function using the template that will find the smallest number among two passed numbers.
Output: