函数模板
1 #include <iostream> 2 using namespace std; 3 4 void myswap01(int& x,int& y) 5 { 6 int temp=0; 7 temp=x; 8 x=y; 9 y=temp; 10 } 11 12 void myswap02(char& x,char& y) 13 { 14 char temp=0; 15 temp=x; 16 x=y; 17 y=temp; 18 } 19 20 template <typename T> 21 void myswap(T& x,T& y) 22 { 23 T temp; 24 temp=x; 25 x=y; 26 y=temp; 27 } 28 29 int main() 30 { 31 int a=10,b=20; 32 char p='P',q='Q'; 33 34 myswap01(a,b); 35 cout<<"a="<<a<<" "<<"b="<<b<<endl; 36 37 myswap02(p,q); 38 cout<<"p="<<p<<" "<<"q="<<q<<endl; 39 40 //显示调用 41 cout<<endl<<endl; 42 myswap<int>(a,b); 43 cout<<"a="<<a<<" "<<"b="<<b<<endl; 44 45 myswap<char>(p,q); 46 cout<<"p="<<p<<" "<<"q="<<q<<endl; 47 48 //自动类型推导,一般很少用 49 cout<<endl<<endl; 50 myswap(a,b); 51 cout<<"a="<<a<<" "<<"b="<<b<<endl; 52 53 myswap(p,q); 54 cout<<"p="<<p<<" "<<"q="<<q<<endl; 55 56 57 return 0; 58 }