c++ - 模板函数重载。理解字符

标签 c++ templates overriding

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

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

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

但这对于旧式 C 字符串是正确的;我认为开发一个函数来检查泛型类型 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;

并且该函数返回一个bool(或者someTestbool 类型),您可以编写(而且,恕我直言,更具可读性和优雅)简单地写

return someTest;

关于c++ - 模板函数重载。理解字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56474775/

相关文章:

c++ - C 解决方案,有人可以向我解释这段代码吗?

c++ - 是否在目标平台上评估了 constexpr?

c++ - 调用模板化成员的模板化方法

java - 接口(interface)作为方法/构造函数参数

c++ - 自定义 C++ 类可以复制内置类型的性能吗?

c++ - 结构作为 unordered_map 的键

c++ - 返回 Boost Graph 中连接的组件子图的列表

c++ - 用于检查给定类型是否存在 istream 运算符 >> 的类型特征

c++ - 当父类没有为自己定义宇宙飞船运算符时覆盖宇宙飞船运算符

javascript - 在框架上注入(inject) javascript