c++之函数模板的局限性

时间:2022-07-23
本文章向大家介绍c++之函数模板的局限性,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
#include<iostream>
using namespace std;

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

//不支持判断自己定义的数据类型
//这里需传入引用
template<class T>
bool myCompare(T &a, T &b) {
    if (a == b) {
        return true;
    }
    else {
        return false;
    }
}
template<> bool myCompare(Person& p1, Person& p2) {
    if (p1.name == p2.name && p1.age == p2.age) {
        return true;
    }
    else
    {
        return false;
    }
}

void test() {
    int a = 10;
    int b = 10;
    bool res = myCompare(a, b);
    cout << res << endl;
    Person p1("tom",10);
    Person p2("tom",10);
    //我们需要具体化Person版本的实现
    bool res2 = myCompare(p1, p2);
    cout << res2 << endl;
}

int main() {
    test();
    system("pause");
    return 0;
}