问题
#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?
回答1:
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);
}
回答2:
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.
来源:https://stackoverflow.com/questions/7279475/call-of-overloaded-maxchar-char-is-ambiguous