从函数重载到函数模板

      函数重载:

 

#include <iostream>
using namespace std;

void swap(int &x, int &y)
{
	int tmp = x;
	x = y;
	y = tmp;
}

void swap(float &x, float &y)
{
	float tmp = x;
	x = y;
	y = tmp;
}

void swap(double &x, double &y)
{
	double tmp = x;
	x = y;
	y = tmp;
}

int main()
{
	int a = 1;
	int b = 2;
	swap(a, b);
	cout << a << endl << b << endl;

	float s = 3.3;
	float t = 4.4;
	swap(s, t);
	cout << s << endl << t << endl;

	double x = 5.5;
	double y = 6.6;
	swap(x, y);
	cout << x << endl << y << endl;

	return 0;
}

       上面的程序,有明显重复的部分,那么,可不可以用int, float和double抽象出来呢?可以的!如下(这个程序有一点点问题):

 

 

#include <iostream>
using namespace std;

template <typename T>
void swap(T &x, T &y)
{
	T tmp = x;
	x = y;
	y = tmp;
}

int main()
{
	int a = 1;
	int b = 2;
	swap(a, b);
	cout << a << endl << b << endl;

	float s = 3.3;
	float t = 4.4;
	swap(s, t);
	cout << s << endl << t << endl;

	double x = 5.5;
	double y = 6.6;
	swap(x, y);
	cout << x << endl << y << endl;

	return 0;
}

        运行一下上面这个程序,发现有错,为什么呢?百思不得其解,查百度吧!找到原因了:这个swap和STL的swap重名了。故改为如下正确程序:

 

#include <iostream>
using namespace std;

template <typename T>
void mySwap(T &x, T &y)
{
	T tmp = x;
	x = y;
	y = tmp;
}

int main()
{
	int a = 1;
	int b = 2;
	mySwap(a, b);
	cout << a << endl << b << endl;

	float s = 3.3;
	float t = 4.4;
	mySwap(s, t);
	cout << s << endl << t << endl;

	double x = 5.5;
	double y = 6.6;
	mySwap(x, y);
	cout << x << endl << y << endl;

	return 0;
}

       至于编译器是如何实现函数模板的,请查看相关书籍。
       

 

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值