14.1.6重学C++之【模板的局限性】

#include<iostream>
#include<stdlib.h>
#include<string>
using namespace std;


/*
    1.2.6模板的局限性
        模板的通用性并不是万能的
*/


// ******************************************
template<class T>
bool my_compare(T & a, T & b){
    if(a == b){
        return true;
    }else{
        return false;
    }
}


void test(){
    int a = 10;
    int b = 20;
    bool result = my_compare(a, b);
    if(result){
        cout << "a==b" << endl;
    }else{
        cout << "a!=b" << endl;
    }
}
// ******************************************


/*
// ******************************************
class Person{
public:
    string name;
    int age;

    Person(string name, int age){
        this->name = name;
        this->age = age;
    }
};


void test_2(){
    Person p1("Tom", 10);
    Person p2("Tom", 10);

    if(my_compare(p1, p2)){ // 报错,无法直接用==比较对象p
        cout << "p1==p2" << endl;
    }else{
        cout << "p1!=p2"<< endl;
    }
}
// ******************************************
// 解决方法1:之前学的运算符重载,重载==
// 解决方法2:具体化
*/


// ******************************************
class Person{
public:
    string name;
    int age;

    Person(string name, int age){
        this->name = name;
        this->age = age;
    }
};


// 利用具体化Person的版本实现代码,具体化优先调用
template<> bool my_compare(Person & a, Person & b){
    if(a.name == b.name && a.age == b.age){
        return true;
    }else{
        return false;
    }
}


void test_2(){
    Person p1("Tom", 10);
    Person p2("Tom", 11);

    if(my_compare(p1, p2)){ // OK
        cout << "p1==p2" << endl;
    }else{
        cout << "p1!=p2"<< endl;
    }
}
// ******************************************


int main(){
    test();
    test_2();
    //利用具体化的模板,可以解决自定义类型的通用化
    //学习模板并不是为了写模板,而是在STL能够运用系统提供的模板

    system("pause");
    return 0;
}

posted @ 2021-04-17 20:08  yub4by  阅读(59)  评论(0)    收藏  举报