forked from Light-City/CPlusPlusThings
-
Notifications
You must be signed in to change notification settings - Fork 0
/
template.cpp
82 lines (71 loc) · 1.67 KB
/
template.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
78
79
80
81
82
//
// Created by light on 19-12-27.
//
#include<iostream>
#include <vector>
#include <cstring>
using namespace std;
// 函数模板
template<typename T>
bool isEqual(T t1, T t2) {
cout << "函数模板" << endl;
return t1 == t2;
}
// 函数模板全特化
template<>
bool isEqual(const char *t1, const char *t2) {
cout << "函数模板全特化" << endl;
return strcmp(t1, t2);
}
// 函数模板偏特化 C++不支持函数模板偏特化 可以重载解决
//template<typename T>
//bool isEqual<T, int>(T a, double b) {
// cout << "函数模板偏特化" << endl;
// return a == b;
//}
// 改为重载 下面是重载!!! 而不是偏特化!
template<typename T>
bool isEqual(T a, double b) {
cout << "函数重载" << endl;
return a == b;
}
/// =============================================================
// 类模板
template<class T>
class comp {
public:
bool isEqual(T t1, T t2) {
cout << "类模板" << endl;
return t1 == t2;
}
};
// 类模板全特化
template<>
class comp<const char *> {
public:
bool isEqual(const char *t1, const char *t2) {
cout << "类模板全特化" << endl;
return strcmp(t1, t2);
}
};
// 类模板偏特化
template<typename T>
class comp<T *> {
public:
bool isEqual(T *t1, T *t2) {
cout << "类模板偏特化" << endl;
return strcmp(t1, t2);
}
};
int main() {
isEqual(1, 2); // 实例化的时候做类型检查
isEqual(1, 2.1);
// isEqual(1.1, 2.1); // 模糊的!
isEqual("qwqw", "asd");
comp<int> c;
c.isEqual(10, 11);
comp<const char *> cc;
cc.isEqual("he", "lo");
comp<char *> p;
p.isEqual("he", "ll");
}