C++模板局限性

#include <iostream>

template<class T>
bool compare(T &a, T &b)
{
   return (a == b);
}

class Person
{
public:
   Person(std::string name, int age):
   name(name),
   age(age)
   {}

   std::string name;
   int age;
};

template<>
bool compare(Person &p1, Person &p2)
{
   return (p1.name == p2.name && p1.age == p2.age);
}

int main()
{
   using namespace std;

   int a = 1;
   int b = 2;
   if(compare(a, b) == true)
   {
      cout << "a == b" << endl;
   }
   else
   {
      cout << "a != b" << endl;
   }

   Person p1("furong", 10);
   Person p2("furong", 10);
   if(compare(p1, p2) == true)
   {
      cout << "p1 == p2" << endl;
   }
   else
   {
      cout << "p1 != p2" << endl;
   }

   return 0;
}
$ ./a.out          
a != b
p1 == p2

学习模板不是为了写模板,而是在STL可以运用系统提供的模板

posted @ 2022-07-13 14:30  thomas_blog  阅读(17)  评论(0编辑  收藏  举报