简体   繁体   English

抑制宏观扩张

[英]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. 我有一个现有的C头文件,它使用#define来定义一组整数,我想将它复制到具有相同值名称的C ++枚举。 For example (using C++11): 例如(使用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. 问题当然是MyEnum::VALUE被转换为MyEnum::0 ,这会导致语法错误。 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. 包括标题后。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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