Compile a function template program to find the maximum value in two data

1. Compile the function template program to find the maximum of the two data;
2. The source code is as follows:

test.cpp

-sharpinclude <iostream>
using namespace std;

template <class T>
T max(T m1, T m2)
{return (m1 > m2)? m1:m2;}

int main() {
    cout << max(2, 5) << "\t" << max(2.0, 5.) << "\t"
         << max("w", "a") << "\t" << max("ABC", "ABD") << endl;

    return 0;
}

3. gPP test.cpp appears:

test.cpp: in function "int main ()":
test.cpp:9:21: error: calling overloaded "max (int, int)" is ambiguous
cout < < max (2,5) < < "t" < max (2.0,5) < < "t"

this is typed according to the book. I don"t know what went wrong. Ask for advice.

CPP
Feb.27,2021

because there is already a max function in the namespace std, the compiler cannot determine which max function you are calling. Just make the following changes.

// test.cpp

-sharpinclude <iostream>
//using namespace std;

template <class T>
T max(T m1, T m2)
{return (m1 > m2)? m1:m2;}

int main() {
    std::cout << max(2, 5) << "\t" << max(2.0, 5.) << "\t"
         << max('w', 'a') << "\t" << max("ABC", "ABD") << std::endl;

    return 0;
}
Menu