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;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
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;
}

- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
- 98
- 99
- 100
- 101
- 102
- 103
- 104
- 105
- 106
- 107
- 108
- 109
- 110
- 111
- 112
- 113
- 114
- 115
- 116
- 117
- 118
- 119
- 120
- 121
- 122
- 123
- 124
- 125