首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

怎么取舍

2012-02-24 
如何取舍一个很简单的交换模版的例子#include iostream#include stringusingnamespacestdtemplate c

如何取舍
一个很简单的交换模版的例子

#include <iostream>
#include <string>
using   namespace   std;

template <class   T>
void   SWAP(T   a,T   b)       //关键地方   问题在后面
{
  T   temp;
  temp=a;   a=b;   b=temp;
}

main()
{
////////////////////////////
int   a=1,b=2;                           //
double   c=3.5,d=4.6;           //
char   e= 'e ',f= 'f ';             //
SWAP(a,b);                         //
SWAP(c,d);                       //
SWAP(e,f);                     //
/////////////////////
system( "pause ");
}

 

使用值传递   void   SWAP(T   a,T   b)     会使效率低下

但是使用       void   SWAP(T&   a,T&   b)   后
就不能这样特化了:   template <>   void   SWAP(T   a[],T   b[]){.........}    

请问如何取舍   或有两全其美的方法

[解决办法]
传值是不能达到交换的目的的,因为传的只是实参的一个拷贝而已,所以LZ一定要传引用或指针,就不存在不好取舍的问题了,选下面这个就行了

void SWAP(T& a,T& b)

热点排行