Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call std::min() when min has been defined as a macro?

Tags:

c++

macros

stl

How do I call std::min when min has already been defined as a macro?

like image 547
user541686 Avatar asked Sep 16 '11 19:09

user541686


People also ask

What is min macro?

The min macro compares two values and returns the smaller one. The data type can be any numeric data type, signed or unsigned. The data type of the arguments and the return value is the same.

Where is std :: min defined?

std::min is defined in the header file <algorithm> and is used to find out the smallest of the number passed to it.


5 Answers

(std::min)(x,y)

The parentheses around min prevent macro expansion. This works with all function macros.

like image 52
Johan Råde Avatar answered Sep 28 '22 13:09

Johan Råde


On Windows, you need to define NOMINMAX before including any windows headers, preferable at the beginning of precompiled header.

like image 30
Andriy Tylychko Avatar answered Sep 28 '22 13:09

Andriy Tylychko


Use #undef min in your code, after #include <> directives.

#include <...> // bad header that defines `min` macro
#ifdef min
#undef min
#endif

// rest f code.

Addendum: If you need to keep the value of the min macro afterwards, you can disable its definition temporarily using a non-portable solution on some compilers. For instance, Microsoft's C++ compiler has a push_macro pragma that also seems to be supported by GCC.

like image 32
André Caron Avatar answered Sep 28 '22 13:09

André Caron


You might be able to avoid the macro definition by:

  • #undef
  • avoid the definition in the first place (either by configuration such as #define NOMINMAX or similar or avoiding including the offending header)

If those options can't be used or you don't want to use them, you can always avoid invoking a function-like macro with an appropriate use of parens:

#include <algorithm>
#include <stdio.h>

#define min(x,y) (((x) < (y)) ? (x) : (y))

int main() 
{
    printf( "min is %d\n", (std::min)( 3, 5));  // note: the macro version of `min` is avoided
}

This is portable and has worked since the dark, early days of C.

like image 32
Michael Burr Avatar answered Sep 28 '22 12:09

Michael Burr


I found a couple of other ways to do it:

Method 1:

using std::min;
min(a, b);   // uses either the macro or the function (don't add side effects!)

Method 2:

#ifndef BOOST_PREVENT_MACRO_SUBSTITUTION
#define BOOST_PREVENT_MACRO_SUBSTITUTION
#endif

...
std::min BOOST_PREVENT_MACRO_SUBSTITUTION(a, b)
like image 28
user541686 Avatar answered Sep 28 '22 12:09

user541686