我正在CPP中尝试使用模板。当我将其与“世界”进行比较时,我不明白为什么会打印“ Hello”?
下面是我的代码段->
#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;
}
输出
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
这里是我使用的C ++版本->
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.
谢谢您的帮助。如果答案太明显,我深表歉意。
"Hello"
和"World"
均为c风格的字符串(类型为const char[6]
),当传递给max
时它们会衰减为const char*
,并且T
也推导为const char*
。因此,比较只是比较指针,即内存地址,重用的是unspecified。
您可以使用strcmp
添加重载或模板专业化以比较c样式的字符串,或者改为使用std::string
,>
my_max(std::string("Hello"), std::string("World")) // name changed because of the conflict with std::max
相反,您可以同时使用两个模板T
和P
。