函数模板
函数模板是通用的函数描述,也就是说,它们使用泛型来定义函数,其中的泛型可以用具体的类型(比如int或double)替换。
函数模板格式
交换两个变量的值
// 声明
template<typename AnyType>
void Swap(AnyType &a, AnyType &b);
// 定义
template<typename AnyType>
void Swap(AnyType &a, AnyType &b);
{
AnyType temp = a;
a = b;
b = temp;
}
解释
- template表示要建立一个模板,并将类型命名为AnyType。
- 关键字template和typename是必须的。也可以使用class代替typename。
- 必须使用尖括号。
- AnyType可以是任意类型。比如int,double…
提示
如果需要多个将同一种算法用于不同类型的函数,请使用模板。
重载的模板
可以像重载常规函数定义那样重载模板定义。和常规重载一样,被重载的模板的函数参数列表必须不同。
实例
#include <iostream>
using std::endl;
using std::cout;
// T可以为任何类型
template<typename T>
void swap(T &a, T &b);
// 也可以使用class
template<class T>
void swap(T *a, T *b, int n);
// 重载的模板
template<class T>
void show(T *a, int n);
int main()
{
int i = 10;
int j = 20;
cout << "交换之前: " << endl;
cout << "i = " << i << endl;
cout << "j = " << j << endl;
swap(i, j); // T 为 int类型
cout << "交换之后: " << endl;
cout << "i = " << i << endl;
cout << "j = " << j << endl;
double x = 12.3;
double y = 21.5;
cout << "交换之前: " << endl;
cout << "x = " << x << endl;
cout << "y = " << y << endl;
swap(x, y); // T 为 double类型
cout << "交换之后: " << endl;
cout << "x = " << x << endl;
cout << "y = " << y << endl;
int int_arr1[10] = {1,2,3,4,5,6,7,8,9,10};
int int_arr2[10] = {10,20,30,40,50,60,70,80,90,100};
cout << "交换之前: " << endl;
cout << "int_arr1: ";
show(int_arr1, 10);
cout << "int_arr2: ";
show(int_arr2, 10);
swap(int_arr1, int_arr2, 10);
cout << "交换之后: " << endl;
cout << "int_arr1: ";
show(int_arr1, 10);
cout << "int_arr2: ";
show(int_arr2, 10);
double double_arr1[10] = {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9,10.1};
double double_arr2[10] = {11.1, 22.2, 32.3, 44.4, 55.5, 66.6, 77.7, 88.8, 99.9,111.1};
cout << "交换之前: " << endl;
cout << "double_arr1: ";
show(double_arr1, 10);
cout << "double_arr2: ";
show(double_arr2, 10);
swap(double_arr1, double_arr2, 10);
cout << "交换之后: " << endl;
cout << "double_arr1: ";
show(double_arr1, 10);
cout << "double_arr2: ";
show(double_arr2, 10);
return 0;
}
template<typename T>
void swap(T &a, T &b)
{
T temp = a;
a = b;
b = temp;
}
template<class 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;
}
}
template<class T>
void show(T *a, int n)
{
for(int i = 0; i < n; i++)
{
cout << a[i] << " ";
}
cout << endl;
}