模板&重载 (例子) (具体化相关)

template <class T>
void Swap(T & a,T & b);              //模板定义
///////////////////////////////////////////////

template void Swap<int>(int,int);    //显示实例化
////////////////////////////////////////////////

template <> void Swap<int>(int,int);//显示具体化2种形式

template <> void Swap(int,int);
//////////////////////////////////////////////


# include <iostream>
template <class T>   //or      template <typename T>
void Swap(T & a,T & b);

template <class T>
void Swap(T * a,T * b,int n);

void show(int a[]);

const int lim=8;

int main()
{
 using namespace std;
    int i=10,j=20;
 cout<<"i,j="<<i<<" "<<j<<endl;
 Swap(i,j);
 cout<<"i,j="<<i<<" "<<j<<endl;

 int d1[lim]={0,5,0,6,1,7,7,8};
 int d2[lim]={0,6,1,2,1,9,9,8};
 show(d1);
 show(d2);
 Swap(d1,d2,lim);
    show(d1);
 show(d2);

 return 0;
}

void show(int a[])
{
 using namespace std;
 cout<<a[0]<<a[1]<<"/";
 cout<<a[2]<<a[3]<<"/";
 for (int i=4;i<lim;i++)
  cout<<a[i];
 cout<<endl;
}

template <class T>
void Swap(T & a,T & b)
{
 T temp;
 temp=a;
 a=b;
 b=temp;
}

template <class T>
void Swap(T * a,T * b,int n)
{
 T temp;
 for(int i=0;i<n;i++)
 {
  temp=a[i];
  a[i]=b[i];
  b[i]=temp;
 }
}

posted @ 2007-02-09 02:32  Edward Xie  阅读(133)  评论(0)    收藏  举报