函數模板的聲明形式為:
template<typename?數據類型參數標識符>
返回類型 ? ? 函數名 ?(參數表)
{
? ? ? ? ? ? ?函數體
}
下面是完整的例子,注意在visual studio2010中用小寫的s的swap做函數名會引起沖突,故筆者使用大寫的Swap,發現能成功編譯。
#include "iostream"
#include "string"
using namespace std;
template <typename SomeType>
void Swap(SomeType &a,SomeType &b)
{
? ? ? ? ? SomeType temp;
? ? ? ? ? temp=a;
? ? ? ? ? ?a=b;
? ? ? ? ? ?b=temp;
}
int main()
{
int A=23;
int B=34;
string strA="You";
string strB="Me";
cout<<A<<" "<<B<<endl;
cout<<strA<<" "<<strB<<endl;
Swap(A,B);
Swap(strA,strB);
cout<<A<<" "<<B<<endl;
cout<<strA<<" "<<strB<<endl;
return 0;
}