c++ - 重载 'min(int&, int&)' 的调用不明确

标签 c++ templates

我在模板上遇到了一些问题。此代码在 vc6 下通过但在 g++ 下失败。 有没有人可以告诉我原因?谢谢。

#include<iostream>
using namespace std;

template<class T>
T min(T x, T y) {
    return (x < y ? x : y);
}

int main() {
    int i1 = 23, i2 = 15, i;
    float f1 = 23.04, f2 = 43.2, f;
    double d1 = 0.421342, d2 = 1.24342343, d;
    i = min(i1, i2);
    f = min(f1, f2);
    d = min(d1, d2);
    cout << "The smaller of " << i1 << " and " << i2 << " is " << i << endl;
    cout << "The smaller of " << f1 << " and " << f2 << " is " << f << endl;
    cout << "The smaller of " << d1 << " and " << d2 << " is " << d << endl;
}

"/usr/bin/make" -f nbproject/Makefile-Debug.mk QMAKE= SUBPROJECTS= .build-conf "/usr/bin/make" -f nbproject/Makefile-Debug.mk dist/Debug/GNU-MacOSX/traincpp mkdir -p build/Debug/GNU-MacOSX rm -f build/Debug/GNU-MacOSX/newmain.o.d g++ -c -g -MMD -MP -MF build/Debug/GNU-MacOSX/newmain.o.d -o build/Debug/GNU-MacOSX/newmain.o newmain.cpp newmain.cpp: In function 'int main()': newmain.cpp:13: error: call of overloaded 'min(int&, int&)' is ambiguous newmain.cpp:5: note: candidates are: T min(T, T) [with T = int] /usr/include/c++/4.2.1/bits/stl_algobase.h:182: note: const _Tp& std::min(const _Tp&, const _Tp&) [with _Tp = int] newmain.cpp:14: error: call of overloaded 'min(float&, float&)' is ambiguous newmain.cpp:5: note: candidates are: T min(T, T) [with T = float] /usr/include/c++/4.2.1/bits/stl_algobase.h:182: note: const _Tp& std::min(const _Tp&, const _Tp&) [with _Tp = float] newmain.cpp:15: error: call of overloaded 'min(double&, double&)' is ambiguous newmain.cpp:5: note: candidates are: T min(T, T) [with T = double] /usr/include/c++/4.2.1/bits/stl_algobase.h:182: note: const _Tp& std::min(const _Tp&, const _Tp&) [with _Tp = double] make[2]: * [build/Debug/GNU-MacOSX/newmain.o] Error 1 make[1]: [.build-conf] Error 2 make: ** [.build-impl] Error 2

生成 失败 (退出值 2, 总计时间: 623毫秒)

最佳答案

这是因为您已经导入了所有 std namespace ,这是一个 no-no .请注意,其他候选者是模板 std::min。删除 using namespace std; 并导入选择符号:

using std::cout;
using std::endl;

或限定他们:

std::cout << "The smaller of " << i1 << " and " << i2 << " is " << i << std::endl;

关于c++ - 重载 'min(int&, int&)' 的调用不明确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5887931/

相关文章:

c++ - 如何确定中间包含 "\0"的 std::string 的长度?

c++ - 您遇到过的最出色的模板用法是什么?

c++ - 如何在 C++ 中为模板类包含非成员运算符重载?

c++ - 如何使用 OpenCV Viz 和 ARUCO 为增强现实应用转换 3D 模型

c++ - 为什么这个程序不消耗内存?

c++ - 在 AVR 中逻辑右移 2 次方的速度更快吗?

c++ - Lambda 函数类型蠕变

C++如何创建指向重载模板函数的函数指针

html - Angular.js 模板到纯 html

jquery - 计算项目 jquery 模板