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

q09*_*987 7 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]
Run Code Online (Sandbox Code Playgroud)

如何更正此错误?

Arm*_*yan 19

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

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

  • @ stinky472:ADL是标准配置.不支持它的编译器应该被丢弃. (2认同)
  • @ stinky472:ADL规则在C++标准中定义明确,并且它们远比复制解析或模板化实例的规则复杂得多.我认为*不依赖于ADL是一种不好的做法,而不是相反 (2认同)

Tom*_*ner 5

我想编译器无法确定是否使用std :: max或你的max,因为你有一个using namespace std; 并且你的max和std :: max都适合账单