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毫秒)
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With