q0987
q0987

Reputation: 35982

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?

Upvotes: 6

Views: 11722

Answers (6)

Tom Tanner
Tom Tanner

Reputation: 9354

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

Upvotes: 5

Richard J. Ross III
Richard J. Ross III

Reputation: 55543

The problem is that there is already a function named 'max' defined by std. To fix this, rename your function to something else, like this:

#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;
}

Upvotes: 2

Asaf
Asaf

Reputation: 4407

That's because there's already std::max template function defined. Remove the 'using namespace std' and add 'std::' where needed., or use '::max'.

Upvotes: 3

Bo Persson
Bo Persson

Reputation: 92261

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.

Upvotes: 4

FatalError
FatalError

Reputation: 54551

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

Upvotes: 4

Armen Tsirunyan
Armen Tsirunyan

Reputation: 132994

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.

Upvotes: 23

Related Questions