I was trying templates in CPP. I could not understand why 'Hello' is being printed when I compare it with 'World'?
Below is my code snippet ->
#include <iostream>
using std::cout;
using std::endl;
template <typename T>
T max(T a, T b){
if(a > b){
return a;
}
else{return b;}
}
int main() {
cout << "max(3, 5): " << max(3, 5) << endl;
cout << "max('a', 'd'): " << max('a', 'd') << endl;
cout << "max(\"Hello\", \"World\"): " << max("Hello", "World") << endl;
return 0;
}
Output
ec2-user:~/environment/cpp_learn/uiuc_cpp/cpp-templates (master) $ make
g++ -std=c++14 -O0 -pedantic -Wall -Wfatal-errors -Wextra -MMD -MP -g -c main.cpp -o .objs/main.o
g++ .objs/main.o -std=c++14 -o main
ec2-user:~/environment/cpp_learn/uiuc_cpp/cpp-templates (master) $ ./main
max(3, 5): 5
max('a', 'd'): d
max("Hello", "World"): Hello
Here is the C++ version that I use ->
ec2-user:~/environment/cpp_learn/uiuc_cpp/cpp-templates (master) $ c++ --version
c++ (GCC) 7.2.1 20170915 (Red Hat 7.2.1-2)
Copyright (C) 2017 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
Thanks in advance for your help. I apologize if the answer is too obvious.
Instead, you can use two templates T
and P
for the same.
#include <iostream>
#include <string>
using std::cout;
using std::endl;
using std::string;
template <typename T,typename P>
T max(T a, P b){
if(a > b){
return a;
}
else{return b;}
}
int main() {
cout << "max(3, 5): " << max(3, 5) << endl;
cout << "max('a', 'd'): " << max('a', 'd') << endl;
cout << "max(\"Hello\", \"World\"): " << max(string("Hello"),string("World")) << endl;
return 0;
}
Compile this modified version. This code is self-explanatory.