-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path12_special.cpp
76 lines (63 loc) · 1.48 KB
/
12_special.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
/*
类模板的全局特化
- 全类特化:特化一个类模板可以特化该类模板所有的成员函数,
相当于重新写了一个针对某种特定数据类型的具体类
声明形式:template<> class 类模板名<类型参数1, ...>{...};
- 成员特化:可以只针对某部分成员函数进行特化
声明形式:template<> 返回值类型 类模板名<类型参数1, ...>::成员函数名(调用参数1, ...){...}
*/
#include <iostream>
#include <cstring>
using namespace std;
// 类模板
template <class T>
class CMath
{
public:
CMath(T const &t1, T const &t2) : m_t1(t1), m_t2(t2) {}
T add()
{
return m_t1 + m_t2;
}
private:
T m_t1;
T m_t2;
};
/*
// 全类特化
template <>
class CMath<char *const>
{
public:
CMath<char *const>(char *const &t1, char *const &t2) : m_t1(t1), m_t2(t2) {}
char *const add()
{
return strcat(m_t1, m_t2);
}
private:
char *const m_t1;
char *const m_t2;
};
*/
// 成员特化
template <>
char *const CMath<char *const>::add()
{
return strcat(m_t1, m_t2);
}
int main()
{
int nx = 10, ny = 20;
CMath<int> m1(nx, ny);
cout << m1.add() << endl;
double dx = 12.3, dy = 45.6;
CMath<double> m2(dx, dy);
cout << m2.add() << endl;
string sx = "hello", sy = "world";
CMath<string> m3(sx, sy);
cout << m3.add() << endl;
char cx[256] = "hello", cy[256] = " world";
CMath<char *const> m4(cx, cy);
cout << m4.add() << endl;
return 0;
}