C++函数的模板

来源:互联网 发布:软件开发交易平台 编辑:程序博客网 时间:2024/05/16 08:39
#include <iostream>using namespace std;template <typename T>void Swap(T &a,T &b);int main(){int i=10;int j=20;cout <<"i,j="<<i<<","<<j<<endl;cout <<"Using compiler-generated int swapper:\n";Swap(i,j);cout <<"Now i,j="<<i<<","<<j<<endl;double x=24.5;double y=81.7;cout <<"x,y="<<x<<","<<y<<endl;cout <<"Using compiler-generated double swapper:\n";Swap(x,y);cout <<"Now x,y="<<x<<","<<y<<endl;return 0;}template <typename T>void Swap(T &a,T &b){T temp;temp=a;a=b;b=temp;}

模板也可以用class  typename==class 是相同的根据个人喜好使用...

#include <iostream>using namespace std;template <class T>void Swap(T &a,T &b);int main(){int i=10;int j=20;cout <<"i,j="<<i<<","<<j<<endl;cout <<"Using compiler-generated int swapper:\n";Swap(i,j);cout <<"Now i,j="<<i<<","<<j<<endl;double x=24.5;double y=81.7;cout <<"x,y="<<x<<","<<y<<endl;cout <<"Using compiler-generated double swapper:\n";Swap(x,y);cout <<"Now x,y="<<x<<","<<y<<endl;return 0;}template <class T>void Swap(T &a,T &b){T temp;temp=a;a=b;b=temp;}


0 0
原创粉丝点击