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

template有关问题 !VS2005下

2012-04-03 
template问题 !VS2005下!#includeiostream#includevector#includestring#includealgorithmusing n

template问题 !VS2005下!
#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
using namespace std;

template<typename T>
inline T max(T t1, T t2)
{
return t1 > t2 ? t1 : t2;
}
template<typename elem_Type>
inline elem_Type max(const vector<elem_Type> &vec)
{
return *max_element(vec.begin(), vec.end());
}
template<typename arrayType>
inline arrayType max(const arrayType *parray, int size)
{
return *max_element(parray, parray+size);
}
int main()
{
string sarr[]={"we", "were", "her", "pride", "of", "ten"};
vector<string> svec(sarr, sarr+6);
int iarr[]={12, 70, 2, 169, 1, 5, 29};
vector<int> ivec(iarr, iarr+7);
double darr[]={2.5,24.8,18.7,4.1,23.9};
vector<double> dvec(darr, darr+5);

int imax = max(max(ivec), max(iarr, 7));
double dmax = max(max(dvec), max(darr, 5));
string smax = max(max(svec), max(sarr, 6));

cout<<"imax should be 169 -- found:"<<imax<<'\n'
<<"dmax should be 24.8 -- found:"<<dmax<<'\n'
<<"smax shoule be were -- found:"<<smax<<'\n';
}
在VS2005中错误如下:
d:\program_shou\a法\6-6.0\bbbbb.cpp(31) : error C2668: “max”: 对重载函数的调用不明确
  d:\program_shou\a法\6-6.0\bbbbb.cpp(8): 可能是“T max<elem_Type>(T,T)”
  with
  [
  T=int,
  elem_Type=int
  ]
  d:\vc8.0\vc\include\xutility(2936): 或“const _Ty &std::max<elem_Type>(const _Ty &,const _Ty &)”
  with
  [
  _Ty=int,
  elem_Type=int
  ]
  试图匹配参数列表“(int, int)”时。。。。。

在线答案!~

[解决办法]

通用算法里有max函数了,直接点就把你的函数名字换下
template <class T> const T& max ( const T& a, const T& b );
template <class T, class Compare>
const T& max ( const T& a, const T& b, Compare comp );


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

template <typename T> 
inline T MyMax(T t1, T t2) 

return t1 > t2 ? t1 : t2; 


template <typename elem_Type> 
inline elem_Type MyMax(const vector <elem_Type> &vec) 

return *max_element(vec.begin(), vec.end()); 


template <typename arrayType> 
inline arrayType MyMax(const arrayType *parray, int size) 

return *max_element(parray, parray+size); 


int main() 

string sarr[]={"we", "were", "her", "pride", "of", "ten"}; 
vector<string> svec(sarr, sarr+6); 
int iarr[]={12, 70, 2, 169, 1, 5, 29}; 
vector<int> ivec(iarr, iarr+7); 
double darr[]={2.5,24.8,18.7,4.1,23.9}; 
vector<double> dvec(darr, darr+5); 

int imax = MyMax(MyMax(ivec), MyMax(iarr, 7)); 
double dmax = MyMax(MyMax(dvec), MyMax(darr, 5)); 
string smax = MyMax(MyMax(svec), MyMax(sarr, 6)); 

cout <<"imax should be 169 -- found:" << imax <<'\n' 
<<"dmax should be 24.8 -- found:" << dmax <<'\n' 


<<"smax shoule be were -- found:" << smax <<'\n'; 


[解决办法]
我曾经也这样栽倒过
就是标准库里已经有个max函数了
把名字改了

热点排行