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:51
#define NOMINMAX

is the trick to suppress the macro definitions of max and min

http://support.microsoft.com/kb/143208

查看更多
地球回转人心会变
3楼-- · 2019-01-07 06:57

No need to define anything, just bypass the macro using this syntax:

(std::min)(a, b); // added parentheses around function name
(std::max)(a, b);
查看更多
爷的心禁止访问
4楼-- · 2019-01-07 07:01

As others mentioned, the errors are due to min/max macros that are defined in windows header(s). There are three ways of disabling them.

1) #define NOMINMAX before including header, this is generally a bad technique of defining macros in order to affect the following headers;

2) define NOMINMAX in compiler command line/IDE. The bad part about this decision is that if you want to ship your sources, you need to warn the users to do the same;

3) simply undefine the macros in your code before they are used

#undef min
#undef max

This is probably the most portable and flexible solution.

查看更多
放我归山
5楼-- · 2019-01-07 07:01

In my case, project did not include windows.h or windef.h explicitly. It was using Boost. So, I resolved the issue by going to the project Properties -> C/C++ -> Preprocessor, and appending NOMINMAX in the Preprocessor Definitions (VS 2013, VS 2015).

查看更多
登录 后发表回答