读书人

linux上练习 c++ 函数模版例子

发布时间: 2012-10-18 13:46:55 作者: rapoo

linux下练习 c++ 函数模版例子

//函数模版使用//函数模版标准不支持参数默认值#include<iostream>#include<cstring>using namespace std;template <typename T>void sort(T* a,int n)//普通冒泡排序{bool changed;do{changed=false;for(int i=1;i<n;i++){if(a[i]<a[i-1]){swap(a[i],a[i-1]);changed=true;}}--n;}while(changed);}template <>//模版特化void sort(const char* a[],int n)//普通冒泡排序{bool changed;do{changed=false;for(int i=1;i<n;i++){if(strcmp(a[i],a[i-1])<0){swap(a[i],a[i-1]);changed=true;}}--n;}while(changed);}//template <typename T>//void show(T t[],int n)template <typename T,int n>void show(T(&t)[n]){//int n=sizeof(t)/sizeof(t[0]);//算出t的个数for(int i=0;i<n;i++)cout<<t[i]<<' ';cout<<endl;}template <typename T>void show(T t){cout<<t<<endl;}int main(){int a[5]={6,7,8,3,2};sort(a,5);//函数模版会自动匹配,不需要显式指定类型show(a);double d=12.345;show(d);char c[5]={'b','f','k','d','a'};sort(c,5);show(c);const char* ca[3]={"fc","ca","ab"};sort(ca,3);show(ca);return 0;}


linux上练习 c++ 函数模版例子

读书人网 >C++

热点推荐