Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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]

How do I correct this error?

like image 970
q0987 Avatar asked Feb 01 '12 14:02

q0987


4 Answers

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.

like image 166
Armen Tsirunyan Avatar answered Nov 11 '22 19:11

Armen Tsirunyan


I guess the compiler can't work out whether to use std::max or your max, because you've got a using namespace std; and both your max and the std::max fit the bill

like image 28
Tom Tanner Avatar answered Nov 11 '22 20:11

Tom Tanner


You're colliding with std::max(). Rename it to something else like mymax and it will work.

like image 28
FatalError Avatar answered Nov 11 '22 18:11

FatalError


You have both your max and std::max. The compiler doesn't know which one you intended to call.

You can tell it by calling ::max(4,5) or std::max(4,5), or - even better - not have using namespace std in the file.

like image 20
Bo Persson Avatar answered Nov 11 '22 18:11

Bo Persson