模板(1)
- 1、非类型模板参数—— 常量(适用于整型数据)
- 2、模板的特化处理(特殊化处理)
1、非类型模板参数—— 常量(适用于整型数据)
#include
#include
#include
using namespace std;
template<class T, size_t N = 10>
class array
{
private:
T _a[N];
};
int main()
{
array<int> a0;
array<int, 100> a1;
array<double, 1000> a2;
return 0;
}
int main()
{
array<int, 10> a1;
int a2[10];
cout << sizeof(a1) << endl;
cout << sizeof(a2) << endl;
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;
};
template<class T>
bool Greater(T left, T right)
{
return left > right;
}
template<>
bool Greater<Date*>(Date* left, Date* right)
{
return *left > *right;
}
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;
}