Aquarius_Girl
Aquarius_Girl

Reputation: 22916

call of overloaded ‘max(char&, char&)’ is ambiguous

#include <iostream>
using namespace std;

int max (int a, int b) 
{ 
   return a<b?b:a; 
} 

template <typename T> T max (T a, T b) 
{ 
   return a<b?b:a; 
} 

template <typename T> T max (T a, T b, T c) 
{ 
   return max (max(a,b), c); 
} 

int main() 
{ 
   // The call with two chars work, flawlessly.
   :: max ('c', 'b');

   // This call with three chars produce the error listed below:
   :: max ('c', 'b', 'a');
   return 0;
}  

Error:

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

Shouldn't this max ('c', 'b', 'a') call the overloaded function with three arguments?

Upvotes: 4

Views: 1386

Answers (2)

cnicutar
cnicutar

Reputation: 182629

Thing is, there is already a max in std, and you are saying using namespace std;:

template <class T> const T& max ( const T& a, const T& b );

So your max ('c', 'b', 'a') is called fine; the problem is inside it.

template <typename T> T max (T a, T b, T c) 
{ 
   return max (max(a,b), c); /* Doesn't know which max to pick. */
}

I don't know why max is available since you didn't include algorithm, but apparently it is.

EDIT

If you want to keep that using at the top:

template <typename T> T max (T a, T b, T c) 
{ 
   return ::max(::max(a, b), c);
} 

Upvotes: 9

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361402

There is NO ambiguous call. http://ideone.com/SJ5Jc (notice the second line is commented)

The problem is : using namespace std : http://ideone.com/T8tsv

It is causing problem, as it brings all symbols into the current namespace, and it seems iostream directly or indirecly includes the header which defines std::max. So when you write ::max in your code, the compiler to unable to decide which max to choose : the one you've written or the one defined by the Standard library.

Remove using namespace std; from your code.

Upvotes: 3

Related Questions