gpt4 book ai didi

c++ - 比较 C++ 模板中的字符串文字

转载 作者:行者123 更新时间:2023-11-30 02:11:05 25 4
gpt4 key购买 nike

我写了一个模板函数来比较两个变量:

template <class t>

int compare(const t &a, const t &b) {

if(a>b) return 1;

if (a<b) return -1;

return 0;

}

int main(int argc, const char *argv[])
{

cout << compare("hi","world");

return 0;

}

出现以下错误

../src/templates.cpp: In function ‘int main(int, const char**)’:
../src/templates.cpp:11: error: no matching function for call to ‘compare(const char [3], const char [6])

请解释。另外,如果我写 cout << compare("hi", "wo");它编译正确。或者如果我删除 &并像int compare(const t a, const t b)这样声明函数它编译。<​​/p>

最佳答案

N 个字符的字符串文字是 N 个常量字符的数组,后面有一个终止符 '\0'。所以 "hi" 的类型是 char const[3]"world" 的类型是 char const[6]

因此,如果将它传递给模板,t 将被推导为两种不同的类型。请注意,在引用参数中,模板参数推导不会将数组转换为指针。

此外,请检查相互比较的指针。你这样做的方式永远不会按词法比较字符串,而只是比较它们的地址,从而产生一个未指定的值。您可以通过使用两个单独的模板参数来修复参数推导位

template <class t, class u>
int compare(const t &a, const u &b) {
if(a>b) return 1;
if (a<b) return -1;

return 0;
}

Clang 给出了一个很好的错误信息

main1.cpp:17:5: error: no matching function for call to 'compare'
compare("hi","world");
^~~~~~~
main1.cpp:4:5: note: candidate template ignored:
deduced conflicting types for parameter 't' ('char [3]' vs. 'char const[6]')
int compare(const t &a, const t &b) {
^
1 error generated.

关于c++ - 比较 C++ 模板中的字符串文字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3917927/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com