#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: call of overloaded ‘max(char&, char&)’ is ambiguous
这个 max ('c', 'b', 'a')
不应该用三个参数调用重载函数吗?
最佳答案
事实是,std
中已经有一个 max
,你说的是 using namespace std;
:
template <class T> const T& max ( const T& a, const T& b );
所以你的 max ('c', 'b', 'a')
被调用得很好;问题出在里面。
template <typename T> T max (T a, T b, T c)
{
return max (max(a,b), c); /* Doesn't know which max to pick. */
}
我不知道为什么 max
可用,因为您没有包含 algorithm
,但显然它是可用的。
编辑
如果您想将 using
保留在顶部:
template <typename T> T max (T a, T b, T c)
{
return ::max(::max(a, b), c);
}
关于c++ - 重载 ‘max(char&, char&)’ 的调用不明确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7279475/