我有一个比较配对值的简单代码。我使用模板函数来减少代码的数量,所以我重载了两次函数(针对不同的情况)。
//cmp.h
template <class T>
bool cmp(T x,T y)
{
if(x == y)
{
return true;
}else
return false;
}
template <class T>
bool cmp(T *x,T *y)
{
if(*x==*y)
{ return true;}else
return false;
}
//main.cpp
#include <iostream>
#include <string>
#include "cmp.h"
using std::cout;
using std::endl;
using std::string;
int main() {
int aInt = 1, bInt = 2;
double aDouble = 3.0, bDouble = 3.0;
char aChars[5] = "haha", bChars[5] = "hahb";
char taChars[6] = "trick", tbChars[6] = "trick";
string aStr = "haha", bStr = "aha";
int* aIntPtr = &aInt, *bIntPtr = &bInt;
cout << cmp(aInt, bInt)<< endl;
cout << cmp(aDouble, bDouble)<< endl;
cout << cmp(aChars, bChars)<< endl;//i can't figure out why char prints out true here ???
cout << cmp(taChars, tbChars)<< endl;
cout << cmp(aStr, bStr)<< endl;
cout << cmp(aIntPtr, bIntPtr)<< endl;
cout << cmp(&aDouble, &bDouble) << endl;
return 0;
} 我的输出是: 0 1 1 1 0 0 1 和我期望: 0 1 0 1 0 0 1
为什么它显示两个字符串是相同的?为什么如果我完全改变这个词,让我们说
char aChars[5] = "jack", bChars[5] = "hahb"; 只有它才能给出正确的结果。我的第二个重载函数不是应该处理这个问题吗?(bool cmp(T *x,T *y))
发布于 2019-06-06 09:39:05
为什么它显示两个字符串是相同的?
因为
template <class T>
bool cmp(T *x,T *y)
{
if(*x == *y)
{
return true;
}else
return false;
} 只检查和y指出的第一个值。
所以当你检查
char aChars[5] = "haha", bChars[5] = "hahb";
cout << cmp(aChars, bChars)<< endl;//检查h是否等于h。
如果要检查字符串之间的相等性(如果要避免使用旧的std::strcmp()),则必须检查所有字符,直到第一个零为止。
但是对于旧风格的C-字符串来说,这是正确的;我认为开发一个函数来检查泛型类型T的指针之间的相等并不是个好主意。
-编辑--
你能指点我吗?
举个例子..。这是很多时候,我不认为在普通C,但如下所示的东西应该是可行的
bool cmp (char const * p1, char const * p2)
{
for ( ; *p1 && *p1 == *p2 ; ++p1, ++p2 )
;
return *p1 == *p2;
}Off主题:您将代码编写为
bool cmp(T *x,T *y)
{
if(*x==*y)
{ return true;}else
return false;
}它相当于
bool cmp(T *x,T *y)
{ return *x == *y; }更一般的说..。如果您有类型的代码
if ( someTest )
return true;
else
return false;函数返回一个bool (或someTest类型为bool),您可以编写(而且,IMHO更易读和更优雅),只需编写
return someTest;发布于 2019-06-06 10:31:28
为什么它显示两个字符串是相同的?
数组衰变为指针,因此char taChars[6]将使用重载template <class T> bool cmp(T *x,T *y),因此只比较第一个元素(在您的情况下是相等的)。
在C++17中,您可以这样做:
template <typename T>
bool cmp(const T& lhs, const T& rhs)
{
if constexpr (std::is_pointer<T>::value) {
return *lhs == *rhs;
} else if constexpr (std::is_array<T>::value) {
return std::equal(std::begin(lhs), std::end(lhs), std::begin(rhs), std::end(rhs));
} else {
return lhs == rhs;
}
}演示
https://stackoverflow.com/questions/56474775
复制相似问题