C++模板函数——VC6下通过,在VS2010下报错 error C2668

来源:互联网 发布:数据完整性稽核 caats 编辑:程序博客网 时间:2024/06/06 00:34

#include <iostream>


using namespace std;

template <typename T>

T max(T a,T b)
{
return (a>b)?a:b;
}

int main()
{
cout<<"Max = "<<max(2,3)<<endl;
cout<<"Max = "<<max(2.1,3.1)<<endl;
cout<<"Max = "<<max(888888888,999999999)<<endl;

return 0;
}

这段代码 VC6 可以正常编译,但VS 2010 下提示如下错误:

1>TesT.cpp(13): error C2668: “max”: 对重载函数的调用不明确
1>          TesT.cpp(6): 可能是“T max<int>(T,T)”
1>          with
1>          [
1>              T=int
1>          ]
1>          C:\Program Files\Microsoft Visual Studio 10.0\VC\include\xutility(2078): 或       “const _Ty &std::max<int>(const _Ty &,const _Ty &)”
1>          with
1>          [
1>              _Ty=int
1>          ]
1>          尝试匹配参数列表“(int, int)”时
1>TesT.cpp(14): error C2668: “max”: 对重载函数的调用不明确
1>          TesT.cpp(6): 可能是“T max<double>(T,T)”
1>          with
1>          [
1>              T=double
1>          ]
1>          C:\Program Files\Microsoft Visual Studio 10.0\VC\include\xutility(2078): 或       “const _Ty &std::max<double>(const _Ty &,const _Ty &)”
1>          with
1>          [
1>              _Ty=double
1>          ]
1>          尝试匹配参数列表“(double, double)”时
1>TesT.cpp(15): error C2668: “max”: 对重载函数的调用不明确
1>          TesT.cpp(6): 可能是“T max<int>(T,T)”
1>          with
1>          [
1>              T=int
1>          ]
1>          C:\Program Files\Microsoft Visual Studio 10.0\VC\include\xutility(2078): 或       “const _Ty &std::max<int>(const _Ty &,const _Ty &)”
1>          with
1>          [
1>              _Ty=int
1>          ]
1>          尝试匹配参数列表“(int, int)”时
1>
1>生成失败。

主要原因是STL中已经含有了max;这里在定义,系统认为是对max的重载,而重载函数必须严格指定类型;

重载函数是在编译时产生代码;而模版是在程序运行时,被编译器调用才产生代码。

0 0
原创粉丝点击