gpt4 book ai didi

c-preprocessor - 延迟宏扩展

转载 作者:行者123 更新时间:2023-12-03 23:18:22 26 4
gpt4 key购买 nike

考虑这个代码:

#define N_ 0
#define N_X 1
#define M(a) N_

M(arg)X; // #1 -- I'd like this to expand to N_X, and ultimately 1; but it's 0X instead
M(arg); // #2 -- this should and does expand to 0

#1 的问题在于,在展开 M() 之后,结果包含 N_,在将其与 X 连接之前,预处理器会找到并展开它。
我能否以某种方式延迟对结果的重新扫描以获得进一步的宏,以便预处理器找到 N_X 而不是 N_?

最佳答案

首先N_ X之间有区别和 N_X .第一个是两个 token 。要形成一个 token ,您必须使用 token 粘贴运算符 ## ,但是这个运算符禁止宏扩展,所以这个:

M(a) ## X //Compiler error can't paste ')' and X

导致编译错误,因为它试图粘贴 M(a)而不是 N_ .您可以通过使用额外级别的宏(这是非常常用的宏)允许宏在粘贴之前扩展:
#define PRIMITIVE_CAT(x, y) x ## y
#define CAT(x, y) PRIMITIVE_CAT(x, y)

但是,在您的情况下,这仍然不起作用:
 CAT(M(a), X) //expands to 0

那是因为,您使用的是对象宏,而不是函数宏。如果您将其更改为函数宏,它将按您的需要工作:
#define N_() 0
#define N_X() 1
#define M(a) N_

CAT(M(arg), X)() // expands to 1
M(arg)() // expands to 0

函数宏更强大,你可以延迟它们的扩展。以下是延迟一次扫描的方法:
#define EMPTY()
#define DEFER(x) x EMPTY()

N_() //Expands to 0
DEFER(N_)() //Expands N_ ()

像这样延迟宏扩展是在预处理器中实现递归的方法之一。

关于c-preprocessor - 延迟宏扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6671344/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com