Enum class scope resolution operator

Viewed 267

When I tried to compile test.cc by g++ test.cc --std=c++14, I got the following error.

test.cc:5:26: error: expected unqualified-id before numeric constant
Colour colour = Colour::None;

test.cc

#include "state.h"
#include <X11/X.h>

int main(){
        Colour colour = Colour::None;
}

state.h

enum class Colour { None, Black, White };

And I found that by #include <X11/X.h>, None is defined as a constant

 #define None                 0L /* universal null resource or null atom */

What bothers me is that I've already used scope resolution operator, namely Colour::None, to specify which None I'm refering, but the error still occurred.

2 Answers

That's life I'm afraid, and it epitomises the reasons for macros being terrible.

Once you've #included <X11/X.h>, the preprocessor will chew up your source code and the compiler will see

Colour colour = Colour::0;

which makes no sense.

One fix would be to #undef None after including the file.

Did you ask a question?

Anyway, one possible direction to proceed, is to refactor your code a little bit. What I would do is

a) perform the "#include < X11/X.h >" in only 1 cpp file, perhaps call it x11x.cpp.

Then, when ever you need to use a function of the X11/X.h code,

2a) add a function declaration (i.e. perhaps 'void foo1(int)') in x11x.hpp.

2b) and implement your 'foo1(int)' to call the "X11/X.h" function in x11x.cpp.

Should have very little impact to performance.

And now the unfortunate macro will only interfere with the code of x11.cpp, so keep this code small.

Related