Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
640 views
in Technique[技术] by (71.8m points)

c++ - error: call of overloaded ‘max(int, int)’ is ambiguous

#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]

How do I correct this error?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It's all because of your using namespace std;. Remove that line. By that using-directive, you bring std::max (which must be somehow included via iostream) into the global scope. Therefore the compiler doesn't know which max to call - ::max or std::max.

I hope this example will be a good scarecrow for those who think that using directives come at no cost. Weird errors are one side effect.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...