警告C4003和错误C2589和C2059:x = std :: numeric_limits <int> :: max();

这行在一个小testing程序中正常工作,但是在我想要的程序中,我得到了下面的编译器投诉:

#include <limits> x = std::numeric_limits<int>::max(); c:\...\x.cpp(192) : warning C4003: not enough actual parameters for macro 'max' c:\...\x.cpp(192) : error C2589: '(' : illegal token on right side of '::' c:\...\x.cpp(192) : error C2059: syntax error : '::' 

我得到相同的结果:

 #include <limits> using namespace std; x = numeric_limits<int>::max(); 

为什么它将max看作macrosmax(a,b); ?

包含定义minmaxmacros的Windows标头时,通常会发生这种情况。 如果您使用的是Windows头文件,请将#define NOMINMAX放入您的代码中,或者使用等效的编译器开关(即使用Visual Studio的/ DNOMINMAX)进行编译。

请注意,使用NOMINMAX会禁用整个程序中的macros。 如果您需要使用minmax操作,请使用<algorithm>标题中的std::min()std::max()

其他的解决scheme是用这样的括号来包装函数名: (std::numeric_limits<int>::max)() 。 同样适用于std::max

不知道这是一个很好的解决scheme… NOMINMAX是更好的国际海事组织,但这可能是在某些情况下的选项。

其他一些头文件正在使用最大macros来污染全局名称空间。 你可以通过定义macros来解决这个问题:

 #undef max x = std::numeric_limits<int>::max(); 
 #ifdef max #pragma push_macro("max") #undef max #define _restore_max_ #endif #include <limits> //... your stuff that uses limits #ifdef _restore_max_ #pragma pop_macro("max") #undef _restore_max_ #endif 

它在Visual Studio 2013中的定义(格式化为更好的间距…)如下所示:

 static _Ty (max)() _THROW0() { // return maximum value return (FLT_MAX); } 

所以我只是使用FLT_MAX。 :)这可能不是一个通用的解决scheme,但对我来说效果很好,所以我想我会分享。

Interesting Posts