std::min gives error

2019-01-07 06:39发布

#include <algorithm>
#include <Windows.h>

int main()
{
    int k = std::min(3, 4);
    return 0;
}

What is windows doing, if I include Windows.h I cant use std::min in visual studio 2005. The error message is:

error C2589: '(' : illegal token on right side of '::'
error C2059: syntax error : '::'

10条回答
手持菜刀,她持情操
2楼-- · 2019-01-07 06:40

The windows.h header file (or more correctly, windef.h that it includes in turn) has macros for min and max which are interfering.

You should #define NOMINMAX before including it.

查看更多
乱世女痞
3楼-- · 2019-01-07 06:40

I still have trouble occasionally with the windows headers and project wide define of NOMINMAX doesn't always seem to work. As an alternative to using parentheses, I sometimes make the type explicit like so:

int k = std::min<int>(3, 4);

This also stops the preprocessor from matching to min and is arguably more readable than the parentheses workaround.

查看更多
走好不送
4楼-- · 2019-01-07 06:43

Try something like this:

#define NOMINMAX
#include <windows.h>

By default, windows.h defines min and max as macros. When those are expanded, code that tries to use std::min (for example) will end up looking something like this:

int k = std::(x) < (y) ? (x) : (y);

The error message is telling you that std::(x) isn't allowed.

查看更多
Evening l夕情丶
5楼-- · 2019-01-07 06:44

For people including windows.h, put the following in effected headers:

#include windows headers ...

pragma push_macro("min")
pragma push_macro("max")
#undef min
#undef max

#include headers expecting std::min/std::max ...

...

pragma pop_macro("min")
pragma pop_macro("max")

In source files just #undef min and max.

#include windows headers ...

#undef min
#undef max

#include headers expecting std::min/std::max ...
查看更多
Ridiculous、
6楼-- · 2019-01-07 06:44

I'd assume windows.h does define min as a macro, e.g. like

#define min(a,b)  ((a < b) ? a : b)

That would explain the error message.

查看更多
来,给爷笑一个
7楼-- · 2019-01-07 06:48

To solve this issue I just create header file named fix_minmax.h without include guards

#ifdef max
    #undef max
#endif

#ifdef min
    #undef min
#endif

#ifdef MAX
    #undef MAX
#endif
#define MAX max

#ifdef MIN
   #undef MIN
#endif
#define MIN min

#include <algorithm>
using std::max;
using std::min;

Basic usage is like this.

// Annoying third party header with min/max macros
#include "microsoft-mega-api.h"
#include "fix_minmax.h"

Pros of this approach is that it works with every kind of included file or part of code. This also saves your time when dealing with code or libraries that depend on min/max macros

查看更多
登录 后发表回答