现在的位置: 首页 > 综合 > 正文

C++函数的模板

2019年01月05日 ⁄ 综合 ⁄ 共 906字 ⁄ 字号 评论关闭
#include <iostream>

using namespace std;
template <typename T>
void Swap(T &a,T &b);

int main()
{
	int i=10;
	int j=20;
	cout <<"i,j="<<i<<","<<j<<endl;
	cout <<"Using compiler-generated int swapper:\n";
	Swap(i,j);	
	cout <<"Now i,j="<<i<<","<<j<<endl;
	
	double x=24.5;
	double y=81.7;
	cout <<"x,y="<<x<<","<<y<<endl;
	cout <<"Using compiler-generated double swapper:\n";
	Swap(x,y);	
	cout <<"Now x,y="<<x<<","<<y<<endl;
	return 0;
}

template <typename T>
void Swap(T &a,T &b)
{
	T temp;
	temp=a;
	a=b;
	b=temp;
}

模板也可以用class  typename==class 是相同的根据个人喜好使用...

#include <iostream>

using namespace std;
template <class T>
void Swap(T &a,T &b);

int main()
{
	int i=10;
	int j=20;
	cout <<"i,j="<<i<<","<<j<<endl;
	cout <<"Using compiler-generated int swapper:\n";
	Swap(i,j);	
	cout <<"Now i,j="<<i<<","<<j<<endl;
	
	double x=24.5;
	double y=81.7;
	cout <<"x,y="<<x<<","<<y<<endl;
	cout <<"Using compiler-generated double swapper:\n";
	Swap(x,y);	
	cout <<"Now x,y="<<x<<","<<y<<endl;
	return 0;
}

template <class T>
void Swap(T &a,T &b)
{
	T temp;
	temp=a;
	a=b;
	b=temp;
}

抱歉!评论已关闭.