在下面的代码中,模板和函数都比较两个字符串并返回较大的一个。然而,尽管代码(定义体)相同,但结果却不同。现在,它可能与获取字符串和字符字符串有关(这是 C++ 错误吗?) - 但为什么模板有区别呢?
#include <iostream>
#include <string>
std::string getBiggerStr(std::string a, std::string b);
template <class T>
T getBigger(T a, T b);
int main() {
std::cout << "\t" << getBiggerStr("Amber", "John") << std::endl;
std::cout << "\t" << getBigger("Amber", "John") << std::endl;
return 0;
}
std::string getBiggerStr(std::string a, std::string b) {
if(a > b) return a;
return b;
}
template <class T>
T getBigger(T a, T b) {
if(a > b) return a;
return b;
}
Run Code Online (Sandbox Code Playgroud)
结果:
John
Amber
Run Code Online (Sandbox Code Playgroud)
为什么不一样呢?模板定义主体是从函数复制粘贴的!