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

小弟我这个程序的重载和模板结合使用有什么东东

2012-02-29 
我这个程序的重载和模板结合使用有什么错误?程序就是这样了,编译的时候显示 thecallofoverloadedfunction

我这个程序的重载和模板结合使用有什么错误?
程序就是这样了,编译的时候显示 "the   call   of   overloaded   function...is   ambiguous "。错在了什么地方?


#include   <iostream>
#include   <string>  
#include   <vector>  
#include   <algorithm>  
#include   <conio.h>

using   namespace   std;  
template   <typename   T>
inline   T   max(   T   t1,   T   t2   )  
              {   return   t1   >   t2   ?   t1   :   t2;   }  
             
template   <typename   Type>
inline   Type   max(   const   vector <Type>   &vec   )  
              {   return   *max_element(   vec.begin(),   vec.end()   );   }  
             
template   <typename   Typename>
inline   Typename   max(   const   Typename   *parray,   int   size   )  
              {   return   *max_element(   parray,   parray+size   );   }  

int   main()   {  
        string   sarray[]={   "we ",   "were ",   "her ",   "pride ",   "of ",   "ten "   };  
        vector <string>   svec(   sarray,   sarray+6   );  

        int   iarray[]={   12,   70,   2,   169,   1,   5,   29   };  
        vector <int>   ivec(   iarray,   iarray+7   );  

        float   farray[]={   2.5,   24.8,   18.7,   4.1,   23.9   };  
        vector <float>   fvec(   farray,   farray+5   );  

        int   imax   =   max(   max(   ivec   ),   max(   iarray,   7   ));  
        float   fmax   =   max(   max(   fvec   ),   max(   farray,   5   ));  
        string   smax   =   max(   max(   svec   ),   max(   sarray,   6   ));  

        cout   < <   "imax   should   be   169     --   found:   "   < <   imax   < <   '\n '  
                  < <   "fmax   should   be   24.8   --   found:   "   < <   fmax   < <   '\n '  
                  < <   "smax   should   be   were   --   found:   "   < <   smax   < <   '\n ';  
        getch();
}


[解决办法]
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>


#include <conio.h>

using namespace std;
//template <typename T>
//inline T max( T t1, T t2 )
// { return t1 > t2 ? t1 : t2; }

template <typename Type>
inline Type max( const vector <Type> &vec )
{ return *max_element( vec.begin(), vec.end() ); }

template <typename Typename>
inline Typename max( const Typename *parray, int size )
{ return *max_element( parray, parray+size ); }

void main() {
string sarray[]={ "we ", "were ", "her ", "pride ", "of ", "ten " };
vector <string> svec( sarray,sarray+6);

int iarray[]={ 12, 70, 2, 169, 1, 5, 29 };
vector <int> ivec( iarray, iarray+7 );

float farray[]={ 2.5, 24.8, 18.7, 4.1, 23.9 };
vector <float> fvec( farray, farray+5 );

int imax = max( iarray, 7 );
float fmax = max( farray, 5 );
string smax = max( svec );

cout < < "imax should be 169 -- found: " < < imax < < '\n ';
cout < < "fmax should be 24.8 -- found: " < < fmax < < '\n ' ;
cout < < "smax should be were -- found: " < < smax < < '\n ';
getch();
}

热点排行
Bad Request.