59

此行在一个小型测试程序中正常工作,但在我想要它的程序中,我收到以下编译器投诉:

#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 视为宏 max(a,b); ?

4

6 回答 6

76

这通常在包含定义 aminmax宏的 Windows 标头时发生。如果您使用的是 Windows 头文件,请放入#define NOMINMAX您的代码,或使用等效的编译器开关进行构建(即,对 Visual Studio 使用/DNOMINMAX)。

请注意,NOMINMAX在整个程序中构建禁用宏。如果需要使用minormax操作,请使用std::min()or std::max()from <algorithm>header。

于 2009-12-15T01:14:42.100 回答
68

其他解决方案是将函数名称用括号括起来,如下所示:(std::numeric_limits<int>::max)(). 同样适用于std::max

不确定这是一个很好的解决方案...... NOMINMAX 是更好的 IMO,但在某些情况下这可能是一种选择。

于 2012-11-26T14:02:06.080 回答
27

其他一些头文件正在使用 max 宏污染全局名称空间。您可以通过取消定义宏来解决这个问题:

#undef max
x = std::numeric_limits<int>::max();
于 2009-12-15T01:11:51.933 回答
3
#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
于 2015-01-23T03:16:16.083 回答
1

(std::numeric_limits::max)()

非常简单。

于 2019-04-10T21:12:31.003 回答
0

它在 Visual Studio 2013 中对我的定义(为更好的间距而格式化...)如下:

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

所以我只是使用 FLT_MAX。:) 这可能不是一个通用的解决方案,但在我的情况下效果很好,所以我想我会分享。

于 2015-05-15T23:01:05.717 回答