How do I deal with the max macro in windows.h colliding with max in std?

Viewed 37989

So I was trying to get valid integer input from cin, and used an answer to this question.

It recommended:

#include <Windows.h> // includes WinDef.h which defines min() max()
#include <iostream>
using std::cin;
using std::cout;

void Foo()
{
    int delay = 0;
    do
    {
        if(cin.fail())
        {
            cin.clear();
            cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        }
        cout << "Enter number of seconds between submissions: ";
    } while(!(cin >> delay) || delay == 0);
}

Which gives me an error on Windows, saying that the max macro doesn't take that many arguments. Which means I have to do this

do
{
    if(cin.fail())
    {
        cin.clear();
#undef max
        cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    }
    cout << "Enter number of seconds between submissions: ";
} while(!(cin >> delay) || delay == 0);

To get it to work. That's pretty ugly; is there a better way to work around this issue? Maybe I should be storing the definition of max and redefining it afterward?

6 Answers

I came here looking for a list of common things that windows.h defines, and after much scouring, I found min, max, small, near, far. Hopefully this helps someone else, too.

I realize this question is 10 years old, but nobody answered with the obvious solution, so here's my way of dealing with this issue.

All OS specific stuff goes in one translation unit (one CPP source file) which provides a cleaner API to the rest of the project, and thus windows.h never pollutes the rest of the project. Any handles to OS stuff is just a "NativeHandle" which is typedef'd to void*; some things are heap allocated this way that wouldn't otherwise need to be possibly, but that's not much of a downside, considering this also provides a single source point for porting to other platforms.

Related