C++函数模板

来源:百度知道 编辑:UC知道 时间:2024/05/29 13:40:46
#include <iostream>
using namespace std;

template <class T>
T max(T x,T y)
{
return ((x>y)?x:y);
}

int main()
{
int i=1,j=2;

cout<<max(i,j)<<endl;

return 0;
}
这段程序应该没什么错误吧,但是在VC2005运行的时候,会出现以下错误:
\muban.cpp(16) : error C2668: 'max' : ambiguous call to overloaded function
1> .\muban.cpp(5): could be 'T max<int>(T,T)'
1> with
1> [
1> T=int
1> ]
1> d:\Program Files\Microsoft Visual Studio 8\VC\include\xutility(2936): or 'const _Ty &std::max<int>(const _Ty &,const _Ty &)'
1> with
1> [
1> _Ty=int
1> ]
1> while trying to match the argument list '(int, int)'

这是为什么呢?期待各位高手教诲!

这个主要是因为在库里面也定义了一个max函数,所以在调用你定义的max函数的时候,编译器不知道是调用库里的版本还是你自定义的版本,所以就报错了。
有两个解决方案:
第一,就是把你自定义的max改动一下函数名,或者改为Max
第二,就是使用作用域符号,调用max的时候这样写: ::max(i,j)