代码之家  ›  专栏  ›  技术社区  ›  Harvey

警告:x=std::numeric_limits<int>::max()上的c4003和错误c2589;

  •  56
  • Harvey  · 技术社区  · 15 年前

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

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

    5 回复  |  直到 10 年前
        1
  •  74
  •   Steve Guidi    15 年前

    当包含定义 min max 宏。如果您使用的是Windows邮件头,请将 #define NOMINMAX 在您的代码中,或使用等效的编译器开关(即使用 /DNIMNMAX 对于Visual Studio)。

    注意建筑物 NOMINMAX 禁止在整个程序中使用宏。如果你需要使用 最大值 操作、使用 std::min() std::max() <algorithm> 标题。

        2
  •  62
  •   denis-bu    12 年前

    另一种解决方案是用括号括住函数名,如下所示: (std::numeric_limits<int>::max)() . 同样适用于 std::max .

    不确定这是解决这个问题的好办法…在我看来,nominmax更好,但在某些情况下,这可能是一种选择。

        3
  •  27
  •   R Samuel Klatchko    15 年前

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

    #undef max
    x = std::numeric_limits<int>::max();
    
        4
  •  3
  •   dmjalund    10 年前
    #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
    
        5
  •  0
  •   Andrew    10 年前

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

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

    所以我只是在使用flt_max.:)这可能不是一个通用的解决方案,但在我的情况下它工作得很好,所以我想我会分享。