C++-------函数模板的局限性

本文深入探讨了C++中模板函数的局限性及其解决方案。通过具体化自定义数据类型,解决了模板函数无法直接比较复杂对象的问题,展示了如何针对特定类型重载模板函数,以实现更广泛的比较操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>
#include <string>

using namespace std;

//模板函数的局限性:
class Person
{
public:
	Person(int age, string name)
	{
		this->m_Age = age;
		this->m_Name = name;
	}

	string m_Name;
	int m_Age;
};

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

void test01()
{
	int a = 10;
	int b = 20;

	int res = myCompare(a, b);
	cout << "res=" << res << endl;

	Person p1(10,"Tom");
	Person p2(20,"Jerry");

	//int res2 = myCompare(p1, p2);//不能进行比较;
	//cout << "res2=" << res2 << endl;
}

//通过具体化自定义数据类型,来解决上述问题:
//相当于告诉编译器。当T为Person类型时,就再走这一条路;
//语法: template <> 返回值 函数名<类型>(参数);
template<> bool myCompare<Person>(Person &a, Person &b)
{
	if (a.m_Age == b.m_Age) {
		return true;
	}
	else {
		return false;
	}
}

void test02()
{
	Person p1(10, "Tom");
	Person p2(20, "Jerry");

	int res2 = myCompare(p1, p2);//不能进行比较;
	cout << "res2=" << res2 << endl;
}
//此时则可运行;
//优先匹配具体化的模板函数;

int main()
{
	test01();
	test02();
	return 0;
}

函数模板不能解决全部问题,此时需要具体化

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值