模板是泛型編程的基礎
一 模板函數
函數模板能夠用來創建一個通用的函數。以支持多種不同的形參。避免重載函數的函數體反覆設計。
template <typename T>
T max(T a,T b)
{
// 函數的主體
return a > b ? a : b;
}
//代替了
int max(int a,int b)
int max(float a,float b)
跟java中的泛型類型
- 有一個int值交換需求
void myswap(int& a, int& b) {
int temp = 0;
temp = a;
a = b;
b = temp;
}
void main() {
int a = 999;
int b = 666;
myswap(a, b);
cout << "a = " << a << " b = " << b << endl;
system("puase");
}
運行結果:a = 666 b = 999
- 由int類型改成交換char 類型
void myswap(char& a, char& b) {
char temp = 0;
temp = a;
a = b;
b = temp;
}
void main() {
char a = 'a';
char b = 'h';
myswap(a, b);
cout << "a = " << a << " b = " << b << endl;
system("pause");
}
結果:a = h b = a
3. c中可以利用模板函數實現
template <typename T>
void myswap(T& a, T& b) {
T temp = 0;
temp = a;
a = b;
b = temp;
}
void main() {
int a = 999;
int b = 666;
myswap(a, b);
cout << "a = " << a << " b = " << b << endl;
char c = 'a';
char d = 'h';
myswap(c, d);
cout << "c = " << c << " d = " << d << endl;
system("pause");
}
運行結果:
a = 666 b = 999
c = h d = a
二 模板類(泛型類)
爲類定義一種模式。使得類中的某些數據成員、默寫成員函數的參數、某些成員函數的返回值,能夠取隨意類型
常見的 容器比如 向量 vector 或 vector 就是模板類
template <class T>
class A
{
public:
A(T a) {
this->a = a;
}
~A() {
}
protected:
T a;
};
template<class T>
class C :public A<T>
{
public:
C(T c,T a):A<T>(a) {
this->c = c;
}
void tell() {
cout << "a:" << a << " c:" << c << endl;
}
private:
T c;
};