preprocessor令牌扩张 [英] Preprocessor token expansion

查看:97
本文介绍了preprocessor令牌扩张的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的preprocessor是如何工作的心智模式显然是不完整的,这是推动我疯了。

My mental model of how the preprocessor works is apparently incomplete, and this is driving me crazy.

欲连接两个令牌,但第二令牌应该被第一膨胀

I want to concatenate two tokens, but the second token should be expanded first.

#define ANSWER 42

#define FOO foo_ ## ANSWER

在这里, FOO 扩展到 foo_ANSWER ,但我希望它是 foo_42 。所以我定义了一个希望合并宏,这会在一定程度扩大参数在连接前:

Here, FOO expands to foo_ANSWER, but I want it to be foo_42. So I define a MERGE macro in the hopes that this would somehow expand the arguments before concatenation:

#define MERGE(x, y) x ## y

#define BAR MERGE(bar_, ANSWER)

BAR 还扩展到 bar_ANSWER 而不是 bar_42 。所以我定义另一个宏辅助

But BAR still expands to bar_ANSWER instead of bar_42. So I define another macro HELPER:

#define HELPER(x, y) MERGE(x, y)

#define BAZ HELPER(baz_, ANSWER)

现在 BAZ 成功地扩展到 baz_42 。目前,这似乎是魔术给我。

And now BAZ is successfully expanded to baz_42. At the moment, this seems like magic to me.

任何人都可以解释这种现象给我?如何扩展规则的工作是什么呢?

Can anyone explain this behavior to me? How do the expansion rules work exactly?

推荐答案

阅读的答案,这里你的问题

Read the answer to your question here:

问题是,当你有一个
  宏替换的preprocessor
  只会扩大宏
  递归如果既字符串化
  操作者#也不令牌粘贴
  操作员##被施加到它。那么你
  必须使用的一些额外的层
  间接,您可以使用
  令牌粘贴运算符和
  递归扩展参数

The problem is that when you have a macro replacement, the preprocessor will only expand the macros recursively if neither the stringizing operator # nor the token-pasting operator ## are applied to it. So, you have to use some extra layers of indirection, you can use the token-pasting operator with a recursively expanded argument

这篇关于preprocessor令牌扩张的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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