C++的std::min and std::max 如:
float_t f(float_t x) const { return std::max((float_t)0.0, x); }
但是使用时如下代码:
#include "windows.h"
#include <algorithm>
void foo() {
int i = 5;
int j = 7;
int x = std::max(i,j);
}
在VS中编译可能会出现以下错误:
1>test.cpp(7) : error C2589: '(' : illegal token on right side of '::'
1>test.cpp(7) : error C2143: syntax error : missing ';' before '::'
这是因为windows.h
中也定义了max和min宏,当你包含了windows.h
时,该程序就不能通过编译。
解决方案:
1. windows.h使用另外一个名字,只适用于windows系统。
int x = _cpp_max(i,j);
int y = _cpp_min(i,j);
该方法在系统库上改动,不推荐。
2. 不使用系统库中的std::max()
和std::min()
函数,用其他代替如:
int x = i > j ? i : j; // max(i,j)
int y = i < j ? i : j; // min(i,j)
简单地重新实现这些函数,如果代码量大,可自己重新写一个不同名称的函数。
3. 添加命名空间using namespace std;
或如下:
using std::min;
using std::max;
int x = max(i,j);
int y = min(i,j);
该方法实验不行,不知是不是我理解错了,欢迎讨论。
4. 使用 std::min<int>
and std::max<int>
如
int x = std::max<int>(i,j);
int y = std::min<int>(i,j);
该方法需要事先知道输入数据类型,但对于i和j类型不同时会出现问题,如:
int i = 5;
unsigned int j = 7;
int x = (std::max)(i,j);
int y = (std::min)(i,j);
会出现以下错误:
1>test.cpp(7) : error C2780: 'const _Ty &std::max(const _Ty &,const _Ty &,_Pr)' :
expects 3 arguments - 2 provided
1> c:program filesmicrosoft visual studio 8vcincludexutility(3190) :
see declaration of 'std::max'
1>test.cpp(7) : error C2782: 'const _Ty &std::max(const _Ty &,const _Ty &)' :
template parameter '_Ty' is ambiguous
1> c:program filesmicrosoft visual studio 8vcincludexutility(3182) :
see declaration of 'std::max'
1> could be 'unsigned int'
1> or 'int'
总结:推荐方法2,自己实现一个相同功能的函数。