Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

#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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...