模板(1)

1、非类型模板参数—— 常量(适用于整型数据)

#include <iostream>
#include <array>
#include <queue>
using namespace std;

//1、非类型模板参数—— 常量(适用于整型数据)
template<class T, size_t N = 10>
class array
{
private:
	T _a[N];
};

int main()
{
	array<int> a0;
	array<int, 100> a1;      // 100
	array<double, 1000> a2;  // 1000

	return 0;
}

int main()
{
	array<int, 10> a1; // C++11
	int a2[10];       // C

	cout << sizeof(a1) << endl;
	cout << sizeof(a2) << endl;

	// 越界都能查出来 —— 函数调用
	// a1[10];
	// a1[15]=0;

	// 指针解引用 —— 抽查是否越界,只针对越界写,越界读不检查
	// a2[10];
	// a2[10]=1;
	// a2[15]=1;


	return 0;
}

2、模板的特化处理(特殊化处理)

struct Date
{
	Date(int year, int month, int day)
		:_year(year)
		, _month(month)
		, _day(day)
	{}

	bool operator>(const Date& d)const
	{
		if ((_year > d._year)
			|| (_year == d._year && _month > d._month)
			|| (_year == d._year && _month == d._month && _day > d._day))
		{
			return true;
		}
		else
		{
			return false;
		}
	}

	int _year;
	int _month;
	int _day;
};

//(1)函数模板的特化
template<class T>
bool Greater(T left, T right)
{
	return left > right;
}

//特化 -- 针对某些类型进行特殊化处理
template<>
bool Greater<Date*>(Date* left, Date* right)
{
	return *left > *right;
}

/
//(2)类模板的特化

namespace jpc
{
	template<class T>
	struct greater
	{
		bool operator()(const T& x1, const T& x2)const
		{
			return x1 > x2;
		}
	};

	//特化:【即使是输入日期的地址,也能比较出各个日期的大小】
	template<>
	struct greater<Date*>
	{
		bool operator()(Date* x1, Date* x2)const
		{
			return *x1 > *x2;
		}
	};

}


int main()
{
	//函数模板
	cout << Greater(1, 2) << endl;  //可以比较,结果正确

	Date d1(2022, 7, 7);
	Date d2(2022, 7, 8);
	cout << Greater(d1, d2) << endl; //可以比较,结果正确

	Date* p1 = &d1;
	Date* p2 = &d2;
	cout << Greater(p1, p2) << endl; //可以比较,结果错误

	//类模板
	jpc::greater<Date> lessFunc1;
	cout << lessFunc1(d1, d2) << endl;

	jpc::greater<Date*> lessFunc2;
	cout << lessFunc2(p1, p2) << endl;


	//优先级队列
	std::priority_queue<Date, vector<Date>, jpc::greater<Date>> dq1;
	std::priority_queue<Date*, vector<Date*>, jpc::greater<Date*>> dq2;

	dq1.push(Date(2022, 9, 27));
	dq1.push(Date(2022, 9, 20));
	dq1.push(Date(2022, 9, 28));
	dq1.push(Date(2022, 9, 26));
	dq1.push(Date(2022, 9, 29));

	while (!dq1.empty())
	{
		const Date& top = dq1.top();
		cout << top._year << "/" << top._month << "/" << top._day << endl;
		dq1.pop();
	}
	cout << endl;


	dq2.push(new Date(2022, 9, 27));
	dq2.push(new Date(2022, 9, 20));
	dq2.push(new Date(2022, 9, 28));
	dq2.push(new Date(2022, 9, 26));
	dq2.push(new Date(2022, 9, 29));

	while (!dq2.empty())
	{
		Date* top = dq2.top();
		cout << top->_year << "/" << top->_month << "/" << top->_day << endl;
		dq2.pop();
	}
	cout << endl;

	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值