如何评估一个嵌套的预处理器宏 [英] How to evaluate a nested preprocessor macro

查看:100
本文介绍了如何评估一个嵌套的预处理器宏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我想选择某个预处理器指令的行为,这个指令在编译时计算一个常量字符串和另一个宏的结果的连接。

  #define CASE1 text1 
#define CASE2 text2
#define CASE3 text3
#define SCENARIO 3
/ **以下内容无效 - for仅用于示例目的** /
#define FUNCTION CASE ## SCENARIO

/ **无论何时写入FUNCTION,我都希望看到text3 ** /

我很难想出一个可行的解决方案,因为预处理器是一次性的野兽。这是可行的吗?

解决方案

可能的是,您只需添加一些额外的宏层。关键在于,当您使用标记粘贴操作符 ## 时,预处理器不会扩展其操作数。但是,如果添加另一层宏,预处理器将展开这些参数。例如:

  #define CASE1 text1 
#define CASE2 text2
#define CASE3 text3
#define SCENARIO 3

#define TOKENPASTE_HELPER(x,y)x ## y
#define TOKENPASTE(x,y)TOKENPASTE_HELPER(x,y)
#define FUNCTION TOKENPASTE(CASE,SCENARIO)

当预处理器扩展 FUNCTION ,它展开 TOKENPASTE 。当它展开 TOKENPASTE 时,它扩展它的arugments(所以 SCENARIO 3 ),因为它的参数都不是令牌粘贴操作符的操作数。接下来,它展开 TOKENPASTE_HELPER ,它执行实际的令牌粘贴操作以制作 CASE3 。最后,它展开 CASE3 宏以获得 text3


let's say I want to select the behaviour of a certain preprocessor directive evaluating at compile time the concatenation of a constant string and the result of another macro.

#define CASE1 text1
#define CASE2 text2
#define CASE3 text3
#define SCENARIO 3
/** the following won't work - for examplification purposes only**/
#define FUNCTION CASE##SCENARIO

/** whenever I write FUNCTION, I expect to see text3 **/

I am having an hard time thinking of a viable solution, as the preprocessor is a one-pass beast. Is that even feasible ?

解决方案

It's possible, you just need to add some extra layers of macros. The key is that when you use the token-pasting operator ##, the preprocessor will not expand its operands. But, if you add another layer of macros, the preprocessor will expand those arguments. For example:

#define CASE1 text1
#define CASE2 text2
#define CASE3 text3
#define SCENARIO 3

#define TOKENPASTE_HELPER(x, y) x ## y
#define TOKENPASTE(x, y) TOKENPASTE_HELPER(x, y)
#define FUNCTION TOKENPASTE(CASE, SCENARIO)

When the preprocessor expands FUNCTION, it expands TOKENPASTE. When it expands TOKENPASTE, it expands its arugments (so SCENARIO gets replaced by 3), since neither of its arguments are operands of the token-pasting operator. Next, it expands TOKENPASTE_HELPER, which does the actual token pasting to make CASE3. Finally, it expands the CASE3 macro to get text3.

这篇关于如何评估一个嵌套的预处理器宏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆