![](/img/trans.png)
[英]Why will std::sort crash if the comparison function is not as operator <?
[英]Why std::string relational operator comparison result is different for a template and a function?
在下面的代码中,模板和函数都比较两个字符串并返回哪个更大。 然而,尽管代码相同(定义体),结果却不同。 现在,它可能与获取字符串与字符串有关(它是 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;
}
结果:
John
Amber
为什么不一样? 模板定义体是从函数中复制粘贴的!
getBigger("Amber", "John")
调用getBigger<const char*>
返回哪个内存地址是更大的数字。
getBigger("Amber", "John")
函数调用中的参数(以及模板参数)的类型是const char*
。 因此,该函数中的比较仅比较两个指针,这不是正确比较(按字典顺序)两个 C 样式字符串的方法。
为了强制使用std::string
作为参数/模板类型,您可以将operator ""s
后缀附加到文字:
using namespace std::string_literals;
int main() {
std::cout << "\t" << getBiggerStr("Amber", "John") << std::endl; // Automatic conversion to std::string
std::cout << "\t" << getBigger("Amber"s, "John"s) << std::endl; // Here, we need to explicitly specify
return 0;
}
或者,如果您没有符合 C++14 的编译器( operator ""s
需要),那么您可以显式构造两个std::string
对象作为参数:
std::cout << "\t" << getBigger(std::string{ "Amber" }, std::string{ "John" }) << std::endl;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.