C++函數模板重載學習筆記

爲什麼要用函數模板重載呢?有的時候並非所有的類型都是用相同的算法,爲了滿足這種需求可以重載常規函數的定義那樣重載模板。

下面是一個簡單的例子:

 

#include <iostream>
#include <string>

using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
template <typename T>
void Swap(T &name,T &age);

template <typename T>
void Swap(T name[],T age[],int id);

template <typename T>
void show(T a[]);

int id=5;
int main(int argc, char** argv) {
	//模板1 
	string age="張三";
	string name="李四";
	Swap(name,age);
	cout <<"name="<<name<<"age=="<<age<<endl;

	//模板2 
	string name1[5]={"張三","劉三","馬疼"};
	string age1[5] ={"45","32","56","60","35"}; 
	Swap(name1,age1,id);
	show(name1);
    show(age1);
	
	return 0;
}

template <typename T>
void show(T a[])
{
	for(int i=0;i<id;i++){
		cout<<a[i]<<endl;
	} 
}

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

template <typename T>
void Swap(T name[],T age[],int id)
{
	T temp;
	for(int i=0;i<id;i++){
		temp=name[i];
		name[i]=age[i];
		age[i]=temp;
	}	
}
 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章