c++ - 重载 ‘max(char&, char&)’ 的调用不明确

标签 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;
}  

错误:

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/

相关文章:

php - 最佳 OOP 实践 PHP/MySQL

c++ - 在 "Modern C++ Design"/Loki 中找到的小对象分配器是否已被弃用以支持更新的实现?

jquery-ui - 在 knockout 计算方法刷新我的 View 后,如何处理样式?

c++ - 在 C++20 中移动 vector

c++ - 在 C++ 中的进程之间共享 CGAL 的几何结构

c++ - 模板 :Name resolution -->can any one tell some more examples for this statement?

c++ - 我们什么时候应该使用方法重载与具有不同命名的方法

c# - 通用与非通用重载调用

c++ - 如何简单解析html引用

c++ - 数组搞砸了 C++