我在模板上遇到了一些问题.这个代码在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;
}
Run Code Online (Sandbox Code Playgroud)
"/ 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.od g ++ -c -g -MMD -MP -MF build/Debug/GNU-MacOSX/newmain.od -o build /Debug/GNU-MacOSX/newmain.o newmain.cpp newmain.cpp:在函数'int main()'中:newmain.cpp:13:错误:调用重载'min(int&,int&)'是不明确的newmain.cpp :5:注意:候选者是:T min(T,T)[含T = int] /usr/include/c++/4.2.1/bits/stl_algobase.h:182:注意:const _Tp&std :: min(const _Tp&,const _Tp&)[with _Tp = int] newmain.cpp:14:error:调用重载'min(float&,float&)'是不明确的newmain.cpp:5:注意:候选者是:T min(T,T) [有T = float] /usr/include/c++/4.2.1/bits/stl_algobase.h:182:注意:const _Tp&std :: min(const _Tp&,const _Tp&)[with _Tp = float] newmain.cpp: 15:错误:调用重载'min(double&,double&)'是不明确的newmain.cpp:5:注意:候选者是:T min(T,T)[含T = double] /usr/include/c++/4.2.1/bits/stl_algobase.h:182:注意:const _Tp&std :: min(const _Tp&,const _Tp&)[with _Tp = double] make [2]:*[build/Debug/GNU-MacOSX/newmain.o]错误1 make [1]:[.build-conf]错误2 make:**[.build-impl]错误2
生成失败(退出值2,总计时间:623毫秒)
out*_*tis 13
这是因为你已经导入了所有std命名空间,这是禁忌.注意其他候选人是模板std::min.删除using namespace std;并导入选择符号:
using std::cout;
using std::endl;
Run Code Online (Sandbox Code Playgroud)
或限定他们:
std::cout << "The smaller of " << i1 << " and " << i2 << " is " << i << std::endl;
Run Code Online (Sandbox Code Playgroud)