简体   繁体   中英

Inhibit macro expansion

Is there any way to inhibit preprocessor macro expansion? I have an existing C header file that uses #define to define a set of integers and I would like to copy it to a C++ enum that has the same value names. For example (using C++11):

enum MyEnum {
  VALUE,
  // ...
};

#define VALUE 0

MyEnum convert(int x) {
  if (x == VALUE) {
    return MyEnum::VALUE;
  }
  // ...
}

The problem of course is that MyEnum::VALUE gets translated to MyEnum::0 , which causes a syntax error. The best solution is to replace the macros with enums, but unfortunately that is not an option in my situation.

I tried to use concatenation, but that didn't help (the compiler gave the same error).

#define CONCAT(a,b) a##b
// ...
return MyEnum::CONCAT(VA,LUE);  // still results in MyEnum::0

Is there another solution that allows me to have the same name for the macro and for the enum value?

You can undefine a macro:

#undef VALUE

after including the header.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM