模板函数重载。理解字符

Template function overloading. Understanding char

我有一个比较一对值的简单代码。我正在使用模板函数来减少代码量,所以我重载了函数两次(针对不同的情况)。

    //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;
        }  

My output is:
0
1
1
1
0
0
1
And i expected:
0
1
0
1
0
0
1

为什么显示两个字符串相同?为什么如果我完全改变这个词,让我们说

char aChars[5] = "jack", bChars[5] = "hahb";  

那么只有它给出正确的结果。我的第二个重载函数不应该处理这个问题吗? (bool cmp(T *x,T *y))

Why it shows that two strings are identical ?

因为

template <class T>
bool cmp(T *x,T *y)
{
   if(*x == *y)
   { 
   return true;
   }else
   return false;
}  

仅检查 xy 指向的 第一个 值。

所以当你检查

 char aChars[5] = "haha", bChars[5] = "hahb";

 cout << cmp(aChars, bChars)<< endl;//

检查 h 是否等于 h

如果你想检查字符串之间的相等性(如果你想避免使用 good-old std::strcmp())你必须检查 all 个字符直到第一个零。

但这对旧样式来说是正确的C-string;我认为开发一个函数来检查泛型类型 T.

的指针之间的相等性不是一个好主意

-- 编辑--

Could u guide me please

举个例子...很多时候我不认为在普通 C 中,但下面的东西应该有效

bool cmp (char const * p1, char const * p2)
 {
   for ( ; *p1 && *p1 == *p2 ; ++p1, ++p2 )
    ;

   return *p1 == *p2;
 }

题外话:你把代码写成

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;

和函数return a bool(或者someTest的类型是bool),你可以这样写(而且,恕我直言,更具可读性和优雅)简单写

return someTest;

Why it shows that two strings are identical ?

数组衰减为指针,因此 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;
    }
}

Demo