prv*_*e17 3 c++ templates string-literals
有人可以解释一下,为什么这段代码中的输出是“C”?
#include <iostream>
using namespace std;
template<class X>
X maximum(X a,X b)
{
if(a > b)
return a;
else
return b;
}
int main() {
cout << maximum("C","D") << endl;
}
Run Code Online (Sandbox Code Playgroud)
请注意,在您的情况下,类型X
将被推断为const char*
,因此您正在比较两个const char *
s,即两个字符串文字的地址。
如果您想获得预期的结果,请使用以下内容
cout << maximum("C"s, "D"s) << endl;
Run Code Online (Sandbox Code Playgroud)
传递std::strings
而不是传递字符串文字的地址。
请参阅字符串文字运算符
或者使用字符而不是使用字符串文字,即'C'
,'D'
并且在这种情况下,X
将被推断为char
.