-
Notifications
You must be signed in to change notification settings - Fork 2
/
templates.cpp
77 lines (65 loc) · 1.49 KB
/
templates.cpp
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
#include <iostream>
int max_v1(int left, int right) {
if (left < right) {
return right;
} else {
return left;
}
};
double max_v1(double left, double right) {
if (left < right) {
return right;
} else {
return left;
}
};
std::string max_v1(std::string left, std::string right) {
if (left < right) {
return right;
} else {
return left;
}
};
template <typename T>
T max_v2(T left, T right) {
if (left < right) {
return right;
} else {
return left;
}
};
class ReminderContainer {
private:
int i_;
public:
ReminderContainer(int i) : i_(i){};
int get() { return i_; };
};
template <>
ReminderContainer max_v2(ReminderContainer left, ReminderContainer right) {
if (left.get() % 10 < right.get() % 10) {
return right;
} else {
return left;
}
};
int main() {
std::cout << max_v1(100, 200) << "\n";
std::cout << max_v1(40.1, 10.2) << "\n";
std::cout << max_v1("left", "right") << "\n";
//
std::cout << "Template version\n";
std::cout << max_v2<int>(100, 200) << "\n";
std::cout << max_v2<double>(40.1, 10.2) << "\n";
std::cout << max_v2<std::string>("left", "right") << "\n";
//
std::cout << "Template version with type deduction\n";
std::cout << max_v2(100, 200) << "\n";
std::cout << max_v2(40.1, 10.2) << "\n";
std::cout << max_v2("left", "right") << "\n";
//
std::cout << "Template specialization\n";
std::cout << max_v2(ReminderContainer(11), ReminderContainer(2)).get()
<< "\n";
return 0;
}