In: Computer Science
Create a generic function max() in C++, to find maximum of 3 generic type arguments, then test this function with char, int and float type.
Program code:
#include<iostream>
using namespace std;
template <typename V> //declaring template V to create generic variables.
// Max function with 3 generic variables as arguments and generic variable as return type.
V Max(V x,V y,V
z)
{
V
res;
//Creating res variable in generic datatype to store max
value.
res=z;
if(x>y &&
x>z)
//Conditions to find maximum value.
res=x;
else if(y>z && y>x)
res=y;
return res;
}
int main()
{
cout << "\nMax(3,7,1) function using
Integer data type :" << Max<int>(3,7,1) <<
endl;
//Max function with integers as arguments.
cout << "\nMax(3.0,6.9,6.8) function using Float data type :" << Max<float>(3.0,6.9,6.8) << endl;
//Max function with float values as arguments.
cout << "\nMax('g','e','z') function using char data type :" << Max<char>('g','e','z') << endl;
//Max function with char values as arguments.
return 0;
}
Output: