为什么两个字符串文字中的最大值输出错误?

问题描述 投票:0回答:3

有人可以解释一下,为什么这段代码中的输出是“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;
}
c++ templates string-literals
3个回答
8
投票

请注意,在您的情况下,类型

X
将被推断为
const char*
,因此您正在比较两个
const char *
,即两个字符串文字的地址。

如果你想得到预期的结果,请使用类似下面的内容

cout << maximum("C"sv, "D"sv) << endl;
// or
cout << maximum<string_view>("C", "D") << endl;

这里比较两个

std::string_view
,这是字典比较,而不是指针比较。

请参阅

std::string_view
比较运算符,并参阅编译器资源管理器中的 演示

或者,使用字符而不是使用字符串文字,即

'C'
'D'
。在这种情况下,
X
将被推导为
char


另请参阅为什么是“using namespace std;”被认为是不好的做法吗?


2
投票

当您使用

maximum("C","D")
时,模板参数为
char const*
。您最终会比较两个指针。无法保证哪个指针更大。你有不确定的行为。

如果你想比较字符串

"C"
和字符串
"D"
,你可以使用:

cout << maximum(std::string("C"), std::string("D")) << endl; // or
cout << maximum("C"s, "D"s) << endl;                         // or
cout << maximum<std::string>("C", "D");

如果您只想比较字符

C
D
,您应该使用

cout << maximum('C', 'D') << endl;

1
投票

如果您希望它也适用于 cstring-literals,请添加专门化。

#include <cstring>

template<class X>
X maximum(X a, X b)
{
    return a > b ? a : b; 
}

template<>
char const* maximum<char const*>(char const* a, char const* b)
{
    return std::strcmp(a, b) > 0 ? a : b;
}
© www.soinside.com 2019 - 2024. All rights reserved.