Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preprocessor macro overriding function definition in c++

I am fairly familiar with the basics of C++, but lack experience (mainly code in Java), so slightly "dumbed down" replies would be appreciated :)

I am extending a larger open source project, which uses a standard visual studio class limits.h, where the following code can be found:

template<> class numeric_limits<double>
    : public _Num_float_base
    {   // limits for type double
public:
    typedef double _Ty;

    static _Ty (max)() _THROW0()
    {   // return maximum value
        return (DBL_MAX);
    }

I have now imported another open source project, which uses minwindef.h which has this piece of code in it:

#ifndef max
#define max(a,b)            (((a) > (b)) ? (a) : (b))
#endif

The build now breaks because for this line

SUMOReal distance = std::numeric_limits<SUMOReal>::max();

the compiler complains about max() being used without any parameters. Is there any quick way to get around this issue, or can I simply not use the library I imported? :/

Hope this was clear enough, thanks for any suggestions!!

like image 439
Samuel Neugber Avatar asked Dec 20 '22 23:12

Samuel Neugber


2 Answers

The only way to get around the problem is to #undef the macro.

This is one of the reasons that macros traditionally are spelled with all UPPER_CASE letter, while system and standard functions are all lower case.

like image 58
Some programmer dude Avatar answered Dec 22 '22 12:12

Some programmer dude


You can prevent C++ preprocessor for expansion of max macro for the specific line of code and then reenable it after the line. This solution would not affect the other parts of code (i.e. if macro max is needed somewhere else):

#pragma push_macro("max")
#undef max
SUMOReal distance = std::numeric_limits<SUMOReal>::max();
#pragma pop_macro("max")
like image 22
Igor Popov Avatar answered Dec 22 '22 11:12

Igor Popov