天天看点

C++模板的局限性

~~

局限性:

~~

*

模板的通用性并不是万能的

例如:

C++模板的局限性

在上述代码中提供的赋值操作,入过传入的a和b是一个数组,就无法实现了

再例如:

C++模板的局限性

在上述代码中,如果T的数据类型传入的是象Person这样的自定义数据类型,也无法正常运行

#include<iostream>
#include <string>
using namespace std;
//模板的局限性
//模板并不是万能的,有些特定数据类型,需要具体话方式做特殊实现
class Person
{
public:
       Person(string name, int age)
       {
              this->m_Name = name;
              this->m_Age = age;
       }
       string m_Name;
       int m_Age;
};
//对比两个数据是否相等函数
template<class T>
bool myCompare(T &a, T&b)
{
       if (a == b)
       {
              return true;
       }
       else
       {
              return false;
       }
}
//利用具体化Person的版本实现代码,具体优先调用
template<>bool myCompare(Person&p1, Person&p2)
{
       if (p1.m_Name == p2.m_Name&&p1.m_Age == p2.m_Age)
       {
              return true;
       }
       else
       {
              return false;
       }
}
void test01()
{
       int a = 10;
       int b = 20;
       bool ret = myCompare(a, b);
       if (ret)
       {
              cout << "a==b" << endl;
       }
       else
       {
              cout << "a!=b" << endl;
       }
}
void test02()
{
       Person p1("Tom", 10);
       Person p2("Tom", 10);
       bool ret = myCompare(p1, p2);
       if (ret)
       {
              cout << "p1==p2" << endl;
       }
       else
       {
              cout << "p1!=p2"<<endl;
       }
}
int main()
{
       //test01();
       test02();
       return 0;
}      

继续阅读