4

I have seen a class where someone named member variables min and max

class A
{
public:
 A();
 ~A();
 bool min;
 bool max;
 ...
};

with a constructor

A::A()
{
  min=false;
  max=true;
  ...
}

I have tried to rewrite it with usage of an initialization list:

A::A():min(false), max(true){}

but I have received an warning + error

warning C4003: not enough actual parameters for macro 'min'
error C2059: syntax error : ')'

because min macro is defined in WinDef.h

Is it possible to use initialization list in this situation without renaming of the member variables?

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
Peter Petrik
  • 9,701
  • 5
  • 41
  • 65

2 Answers2

5

If you have VS2013 or another modern compiler:

A():min {false}, max {true} { }

avoids the problem because min(a,b) is a function-style macro and { can't start its argument list.

This is specific to initializer lists, so I've reopened the question. The "duplicate" suggested addresses macro use in expression context, which is fundamentally different - you can use (min) there.

MSalters
  • 173,980
  • 10
  • 155
  • 350
1

Depending on your situation you have several options.

  1. Use brace initialisation as suggested by @MSalters

  2. Define NOMINMAX before you include the windows header files to avoid the min and max macros from being defined. This will depend on how big your code is and how much control you have over it.

  3. Just #undef the macros. Only recommend in a source file.

  4. Use MSVC pre-processor directives to save, undef then restore the macros. Like so...

    #pragma push_macro("min")
    #undef min
    /* use min here */
    #pragma pop_macro("min")
    
Lionel
  • 326
  • 1
  • 4
  • The downside to defining `NOMINMAX` is that other sources might be expecting `min` and `max` to exist. – Mike DeSimone Oct 01 '14 at 13:53
  • @MikeDeSimone Yes exactly, the same is true for using `#undef`, you have to be careful where you put that and what code could potentially be compiled after. – Lionel Oct 01 '14 at 13:59
  • 1
    @MikeDeSimone: That might be solved by a further `using std::min; using std::max`. It's quite uncommon for code to depend on `min` and `max` being macro's. – MSalters Oct 02 '14 at 07:11