C++函数模板学习

函数模板

函数模板是通用的函数描述,也就是说,它们使用泛型来定义函数,其中的泛型可以用具体的类型(比如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;
}

解释

  1. template表示要建立一个模板,并将类型命名为AnyType。
  2. 关键字template和typename是必须的。也可以使用class代替typename。
  3. 必须使用尖括号。
  4. 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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值