为什么要用函数模板重载呢?有的时候并非所有的类型都是用相同的算法,为了满足这种需求可以重载常规函数的定义那样重载模板。
下面是一个简单的例子:
#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; } }