函數(shù)模板的聲明形式為:
template<typename?數(shù)據(jù)類型參數(shù)標(biāo)識(shí)符>
返回類型 ? ? 函數(shù)名 ?(參數(shù)表)
{
? ? ? ? ? ? ?函數(shù)體
}
下面是完整的例子,注意在visual studio2010中用小寫的s的swap做函數(shù)名會(huì)引起沖突,故筆者使用大寫的Swap,發(fā)現(xiàn)能成功編譯。
#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;
}