简体   繁体   English

宏的生成取决于预处理器的条件

[英]Macro generation depending on preprocessor conditionals

I have a situation like the following, where I have entries in a table with a macro: 我遇到以下情况,其中我在带有宏的表中具有条目:

#define FOR_MY_TYPES(apply) \
  apply(a, b, c) \
  apply(d, e, f) \
  ....

I also have some preprocessor conditionals: 我也有一些预处理条件:

#define CONDITION1 1
#define CONDITION2 0

I want that some entries in the table are added depending on these conditions, something like this: 我希望根据这些条件在表中添加一些条目,如下所示:

#define FOR_MY_TYPES(apply) \
    apply(a, b, c) \
    #if CONDITION1 || CONDITION2
    apply(x, y, z)
    #endif

What is the best way to achieve this keeping only one macro definition, and, if possible, avoid duplicating entries depending on conditions. 实现此目的的最佳方法是仅保留一个宏定义,并且如果可能,请避免根据条件重复条目。 I want to avoid this: 我想避免这种情况:

#if CONDITION1
#define FOR_MY_TYPES(apply) \
   ....Full table here...
#endif
#if CONDITION2
#define FOR_MY_TYPES(apply) \
//Full table again + CONDITION2 types
#endif
#if CONDITION1 || CONDITION2
#define FOR_MY_TYPES(apply) \
//Full table again + CONDITION1 || CONDITION2 types
#endif

My problem is that there are quite a few combinations, so I should avoid replicating as much as possible. 我的问题是有很多组合,所以我应该避免尽可能多地复制。 It is also more error-prone. 这也更容易出错。

One possible approach: 一种可能的方法:

#if CONDITION1 || CONDITION2
#define really_apply(x) x
#else
#define really_apply(x)
#endif

#define FOR_MY_TYPES(apply) \
    apply(a, b, c) \
    really_apply(apply(x, y, z))

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

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