文章目录
- 1.非类型模板参数的引入
- 2.标准库和普通数组
- 3.模板的特化
1.非类型模板参数的引入
template<class T, size_t N = 10>
class array
{
private:T _a[N];
};int main()
{array<int> a1;array<int, 100> a2;array<double, 1000> a3;return 0;
}
2.标准库和普通数组
int main()
{array<int, 10> a1; int a2[10] = { 0 };return 0;
}
3.模板的特化
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <list>
#include <vector>
#include <algorithm>
#include <array>
#include <time.h>
#include <queue>
#include <stdbool.h>
using namespace std;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;}}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;
};
template<class T>
bool Greater(T left, T right)
{return left > right;
}
template<>
bool Greater<Date*>(Date* left, Date* right)
{return *left > *right;
}
namespace apex
{template<class T>struct less{bool operator()(const T& left, const T& right) const{return left < right;}};template<>struct less<Date*>{bool operator()(Date* d1, Date* d2) const{return *d1 < *d2;}};
}int main()
{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; apex::less<Date> ls1;cout << ls1(d1, d2) << endl;apex::less<Date*> ls2;cout << ls2(p1, p2) << endl;std::priority_queue<Date, vector<Date>, apex::less<Date>> dq1;std::priority_queue<Date*, vector<Date*>, apex::less<Date*>> dq2;dq2.push(new Date(2023, 8, 9));dq2.push(new Date(2023, 8, 10));dq2.push(new Date(2023, 8, 12));dq2.push(new Date(2023, 8, 13));return 0;
}