Possible problems with NOMINMAX on Visual C++

前端 未结 4 1911
青春惊慌失措
青春惊慌失措 2020-11-29 05:18

What problems could I get when defining NOMINMAX before anything else in my program?

As far as I know, this will make not

相关标签:
4条回答
  • 2020-11-29 05:31

    For precompiled header (like stdafx.h) I use this:

    #define NOMINMAX
    #include <algorithm>
    #include <Windows.h>
    #ifndef min
    #define min(x,y) ((x) < (y) ? (x) : (y))
    #endif
    #ifndef max
    #define max(x,y) ((x) > (y) ? (x) : (y))
    #endif
    #include <gdiplus.h>
    #undef min
    #undef max
    
    0 讨论(0)
  • 2020-11-29 05:41

    I got fix issue by declaring the headers and namespaces in the following order:

    #include <windows.h>
    #include <minmax.h>
    #include <gdiplus.h>
    
    using namespace Gdiplus;
    using namespace std;
    
    0 讨论(0)
  • 2020-11-29 05:48

    I generally use NOMINMAX like this to limit the potential side effects:

    #define NOMINMAX
    #include <windows.h>
    #undef NOMINMAX
    

    That way the scope of the NOMINMAX is relatively confined.

    It's not a perfect solution. If something else has already defined NOMINMAX, this pattern fails (though I've never encountered such a case).

    If you want to be really, really careful, then you can #include a wrapper header wherever you would have #included windows.h. The wrapper would go something like this:

    /* Include this file instead of including <windows.h> directly. */
    #ifdef NOMINMAX
    #include <windows.h>
    #else
    #define NOMINMAX
    #include <windows.h>
    #undef NOMINMAX
    #endif
    

    You could imagine doing other things in the wrapper, too, like enforcing UNICODE and/or STRICT.

    0 讨论(0)
  • 2020-11-29 05:54

    Using NOMINMAX is the only not-completely-evil way to include <windows.h>. You should also define UNICODE and STRICT. Although the latter is defined by default by modern implementations.

    You can however run into problems with Microsoft’s headers, e.g. for GdiPlus. I’m not aware of problems with headers from any other companies or persons.

    If the header defines a namespace, as GdiPlus does, then one fix is to create a wrapper for the relevant header, where you include <algorithm>, and inside the header’s namespace, using namespace std; (or alternatively using std::min; and using std::max):

    #define NOMINMAX
    #include <algorithm>
    namespace Gdiplus
    {
      using std::min;
      using std::max;
    }
    

    Note that that is very different from a using namespace std; at global scope in header, which one should never do.

    I don’t know of any good workaround for the case where there's no namespace, but happily I haven’t run into that, so in practice that particular problem is probably moot.

    0 讨论(0)
提交回复
热议问题