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 @   yub4by  阅读(55)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示