错误:重载'max(int,int)'的调用是不明确的

时间:2012-02-01 14:28:44

标签: c++ stl

#include <iostream>

using namespace std;

template<typename T>
T max(T lhs, T rhs)
{
  return lhs < rhs ? rhs : lhs;
}
template<>
int max<int>(int lhs, int rhs)
{
  return lhs < rhs ? rhs : lhs;
}

int main()
{
  cout << max<int>(4, 5) << endl;

}

~/Documents/C++/boost $ g++ -o testSTL testSTL.cpp -Wall
testSTL.cpp: In function ‘int main()’:
testSTL.cpp:18:24: error: call of overloaded ‘max(int, int)’ is ambiguous
testSTL.cpp:11:5: note: candidates are: T max(T, T) [with T = int]
/usr/include/c++/4.5/bits/stl_algobase.h:209:5: note:                 const _Tp& std::max(const _Tp&, const _Tp&) [with _Tp = int]

如何更正此错误?

6 个答案:

答案 0 :(得分:19)

这完全是因为你的using namespace std;。删除该行。 通过using指令,您可以将std::max(必须以某种方式通过iostream包含在内)引入全局范围。因此,编译器不知道要调用哪个max - ::maxstd::max

我希望这个例子对于那些认为使用指令是免费的人来说将是一个很好的稻草人。奇怪的错误是一个副作用。

答案 1 :(得分:5)

我猜编译器无法确定是使用std :: max还是你的max,因为你有一个using namespace std;你的max和std :: max都符合账单

答案 2 :(得分:4)

您正在与std::max()发生碰撞。将其重命名为mymax之类的其他内容,它将起作用。

答案 3 :(得分:4)

您有maxstd::max。编译器不知道您打算调用哪一个。

您可以通过致电::max(4,5)std::max(4,5)告诉您,或者 - 甚至更好 - 在文件中没有using namespace std

答案 4 :(得分:3)

那是因为已经定义了std :: max模板函数。 删除'using namespace std'并在需要的地方添加'std ::',或使用':: max'。

答案 5 :(得分:2)

问题是已经有一个名为&#39; max&#39;由标准定义。要解决此问题,请将您的函数重命名为其他内容,例如:

#include <iostream>

using namespace std;

template<typename T>
T mymax(T lhs, T rhs)
{
    return lhs < rhs ? rhs : lhs;
}
template<>
int mymax<int>(int lhs, int rhs)
{
    return lhs < rhs ? rhs : lhs;
}

int main()
{
    cout << mymax<int>(4, 5) << endl;

    return 0;
}
相关问题