Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
374 views
in Technique[技术] by (71.8m points)

c++ - call of overloaded 'min(int&, int&)' is ambiguous

I got some problem on template.This code passed under vc6 but failed under g++. Is there anybody could tell me the reason? thanks.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It's because you've imported all of the std namespace, which is a no-no. Note the other candidates are template std::min. Remove the using namespace std; and either import select symbols:

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

or qualify them:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...