c++ - 为什么模板函数调用不明确?

标签 c++ templates

#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)

那么问题是什么?为什么我得到

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/

相关文章:

c++ - 未定义的模板方法技巧?

c++ - 在 Ubuntu OS 的 C++ 程序中包含 <queue>

c++ - C++:如何获取位集的MSB(最高有效位)(使用按位运算符)?

android - 使用 libvpx x86 android 构建项目失败并出现 undefined reference 错误

c++ 为什么当前面的步骤抛出异常时,std::shared_ptr 的指针引用会被销毁

c++ - 模板模板参数用作其他参数的默认值

c++ - 销毁与取消分配

c++ - 运算符重载 = 和模板 double 值仅对 int 不起作用

c++ - 模板类的隐式转换

c++ - 可变参数模板和 std::array 意外行为