调用重载'max(char&,char&)'是不明确的

Aqu*_*irl 3 c++ templates overloading

#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;
}  
Run Code Online (Sandbox Code Playgroud)

错误:

error: call of overloaded ‘max(char&, char&)’ is ambiguous
Run Code Online (Sandbox Code Playgroud)

不应该max ('c', 'b', 'a')用三个参数调用重载函数吗?

cni*_*tar 8

事情是,已经有一个maxstd你说using namespace std;:

template <class T> const T& max ( const T& a, const T& b );
Run Code Online (Sandbox Code Playgroud)

所以你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. */
}
Run Code Online (Sandbox Code Playgroud)

我不知道为什么max可用,因为你没有包括algorithm,但显然它是.

编辑

如果你想保持using在顶部:

template <typename T> T max (T a, T b, T c) 
{ 
   return ::max(::max(a, b), c);
} 
Run Code Online (Sandbox Code Playgroud)

  • @Anisha Kaul因为`::`指定"我想使用*my*`max`". (2认同)