#include <iostream>
using namespace std;
template <typename T>
T max(T x, T y)
{
return (x > y) ? x : y;
}
int main()
{
cout << max(3, 7) << std::endl;
cout << max(3.0, 7.0) << std::endl;
cout << max(3, 7.0) << std::endl;
return 0;
}
我在这里期待 max 的实例
cout << max(3, 7) << std::endl; // max (int, int)
cout << max(3.0, 7.0) << std::endl; // max (double, double)
cout << max(3, 7.0) << std::endl; // max(int, double)
那么问题是什么?为什么我得到 p>
11 25 [Error] call of overloaded 'max(double, double)' is ambiguous
最佳答案
如果您完整查看编译错误,就会明白原因。这是 gcc 5.2 给我的:
main.cpp: In function 'int main()':
main.cpp:10:21: error: call of overloaded 'max(int, int)' is ambiguous
cout << max(3, 7) << std::endl;
^
main.cpp:4:3: note: candidate: T max(T, T) [with T = int]
T max(T x, T y)
^
In file included from /usr/local/include/c++/5.2.0/bits/char_traits.h:39:0,
from /usr/local/include/c++/5.2.0/ios:40,
from /usr/local/include/c++/5.2.0/ostream:38,
from /usr/local/include/c++/5.2.0/iostream:39,
from main.cpp:1:
/usr/local/include/c++/5.2.0/bits/stl_algobase.h:219:5: note: candidate: constexpr const _Tp& std::max(const _Tp&, const _Tp&) [with _Tp = int]
max(const _Tp& __a, const _Tp& __b)
^
基本上有两个max
函数 - 你的和 std::max
,它包含在其他 #include
的一些链中来自 <iostream>
.后者是通过查找找到的,因为你
using namespace std;
实际上,我们有:
template <typename T> T max(T, T); // yours
template <typename T> T const& max(T const&, T const&); // std
没有一个比另一个更好,因此模棱两可。这是avoid using namespace std
的一个很好的理由.或者在标准库函数方面不重新发明轮子的一个很好的理由 - 只需使用 std::max
.或两者。
另一方面,这个
max(3, 7.0)
无论模板推导失败如何,都会失败。它会推断出 T
作为int
对于第一个参数,T
作为double
第二个 - 但只能有一个 T
!您必须显式调用 max<int>(3, 7.0)
或 max<double>(3, 7.0)
绕过演绎失败,这取决于你想投两个参数中的哪一个。
关于c++ - 为什么模板函数调用不明确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32463047/