My professor has given me this assignment.
Implement a generic function called Max, which takes 3 arguments of generic type and returns maximum out of these 3. Implement a specialized function for char* types.
Here's my code :
#include <iostream>
#include <string>
using namespace std;
template<typename T>
T Max(T first,T second,T third )
{
if(first > second)
{
if(first > third)
{
return first;
}
else
{
return third;
}
}
else if(second > third)
{
return second;
}
else
{
return third;
}
}
template<>
char* Max(char* first,char* second,char* third)
{
if(strcmp(first, second) > 0)
{
if(strcmp(first, third) > 0)
{
return first;
}
else
{
return third;
}
}
else if(strcmp(second, third) > 0)
{
return second;
}
else
{
return third;
}
}
int main(void)
{
cout << "Greatest in 10, 20, 30 is " << Max(10, 20, 30) << endl;
char a = 'A';
char b = 'B';
char c = 'C';
char Cptr = *Max(&a, &b, &c);
cout << "Greatest in A, B ,C is " << Cptr << endl;
string d = "A";
string e = "B";
string f = "C";
string result = *Max(&d, &e, &f);
cout << "Greatest in A, B, C is " << result << endl;
}
Output :
Greatest in 10, 20, 30 is 30
Greatest in A, B ,C is C
Greatest in A, B, C is A
Problem :
If I pass char datatypes in Max function A, B, C, it returns C, but if I pass string datatypes A, B, C it returns A.
Why does it return A here?
Thanks.