函数模板的局限性

3.1 模板不能解决所有的类型
3.2 如果出现不能解决的类型,可以通过第三地具体化来解决问题
3.3 template<> 返回值 函数名<具体类型>(参数)

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<string>
using namespace std;

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

#if(0)
	bool operator==(const Bachelor& bachelor) {
		if (this->m_age == bachelor.m_age && 
			this->m_name.compare(bachelor.m_name) == 0) {
			return true;
		}
		return false;
	}
#endif

	string m_name;
	int m_age;
};

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

#if(1)
template<> bool myCompare<Bachelor>(Bachelor &a, Bachelor &b) {
	if (a.m_age == b.m_age && a.m_name.compare(b.m_name) == 0) {
		return true;
	}
	return false;
}
#endif

void test01() {
	Bachelor b("Nick", 25);
	Bachelor b1("Nick", 25);
	Bachelor b2("Judy", 26);

	if (myCompare(b1, b)) {
		cout << "相等" << endl;
	}
	else {
		cout << "不相等" << endl;
	}
}

int main(){
	test01();
	
	system("pause");
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值