函數模板
一個函數模板就是一個創建函數的藍圖或者公式。
例如,我們希望編寫一個函數來比較兩個值(值類型可能爲int型、double型、string型……),由於值類型繁多,所以我們必須編寫多個函數,每個函數比較一種給定類型的值。
但是,如果我們使用函數模板,通過函數模板這個藍圖生成針對特定類型的函數版本,那我們的工作量將大大減少。
#include <iostream>
using namespace std;
template <typename T>
void Swap(T &a , T &b)
{
T temp;
temp = a;
a = b;
b = temp;
}
int main() {
int i = 10;
int j = 20;
cout << "Original:" << endl;
cout << "i = " << i << "j = " << j << endl;
Swap(i , j);
cout <<"Swapped: " << endl;
cout << "i = " << i << "j = " << j << endl;
double m = 10.10;
double n = 20.20;
cout << "Original:" << endl;
cout << "m = " << m << "n = " << n << endl;
Swap(m , n);
cout <<"Swapped: " << endl;
cout << "m = " << m << "n = " << n << endl;
}
函數模板與重載
#include <iostream>
using namespace std;
const int Lim = 8;
template <typename T>
void Swap(T &a , T &b)
{
T temp;
temp = a;
a = b;
b = temp;
}
template <typename T>
void Swap(T a[] , T b[] , int n)
{
T temp;
for (int i = 0; i < n; ++i) {
temp = a[i];
a[i] = b[i];
b[i] = temp;
}
}
void show(int a[])
{
cout << a[0] << a[1] << "/";
cout << a[2] << a[3] << "/";
for (int i = 4; i < Lim ; ++i)
cout << a[i];
cout << endl;
}
int main() {
int i = 10;
int j = 20;
cout << "i = " << i << "j = " << j << endl;
Swap(i , j);
cout << "i = " << i << "j = " << j << endl;
int d1[Lim] = {0,7,0,4,1,7,7,6};
int d2[Lim] = {0,7,2,0,1,9,6,9};
show(d1);
show(d2);
Swap(d1 , d2 , Lim);
show(d1);
show(d2);
}
顯示具體化模板函數
#include <iostream>
using namespace std;
struct job
{
char name[40];
double salary;
int floor;
};
template <typename T>
void Swap(T &a , T &b)
{
T temp;
temp = a;
a = b;
b = temp;
}
template <> void Swap<job> (job &j1 , job &j2)
{
double t1;
int t2;
t1 = j1.salary;
j1.salary = j2.salary;
j2.salary = t1;
t2 = j1.floor;
j1.floor = j2.floor;
j2.floor = t2;
}
void show(job &j)
{
cout << j.name << ": $" << j.salary << " on floor " << j.floor << endl;
}
int main()
{
int i = 10 , j = 20;
cout << " i , j = " << i << "," << j << endl;
Swap(i , j);
cout << " i , j = " << i << "," << j << endl;
job sue = {"susan yaffe" , 73000.60 , 7};
job sidney = {"sidney taffe" , 78060.72 , 9};
show(sue);
show(sidney);
Swap(sue , sidney);
show(sue);
show(sidney);
}