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;
}


 

posted @ 2012-10-13 11:48  真爱无限  阅读(230)  评论(0编辑  收藏  举报