gpt4 book ai didi

c++ - 为什么在重新扫描期间没有替换参数替换?

转载 作者:IT老高 更新时间:2023-10-28 23:15:24 26 4
gpt4 key购买 nike

考虑以下宏定义和调用:

#define x x[0]
#define y(arg) arg

y(x)

此调用扩展为 x[0](在 Visual C++ 2010、g++ 4.1、mcpp 2.7.2 和 Wave 上测试)。

为什么?具体来说,为什么不展开成x[0][0]

在宏替换期间,

A parameter in the replacement list...is replaced by the corresponding argument after all macros contained therein have been expanded. Before being substituted, each argument’s preprocessing tokens are completely macro replaced (C++03 §16.3.1/1).

评估宏调用,我们采取以下步骤:

  • 类函数宏 yx 作为其 arg 参数的参数调用
  • 参数中的x被宏替换为x[0]
  • 替换列表中的 arg 被替换为参数的宏替换值 x[0]

所有参数替换后的替换列表为x[0]

After all parameters in the replacement list have been substituted, the resulting preprocessing token sequence is rescanned...for more macro names to replace (C++03 §16.3.4/1).

If the name of the macro being replaced is found during this scan of the replacement list...it is not replaced. Further, if any nested replacements encounter the name of the macro being replaced, it is not replaced (C++03 §16.3.4/2).

替换列表x[0]被重新扫描(注意被替换的宏的名字y):

  • x 被标识为类对象宏调用
  • x 替换为 x[0]

由于 §16.3.4/2 中的规则阻止递归,替换在此时停止。重新扫描后的替换列表为x[0][0]

我显然误解了一些东西,因为我测试过的所有预处理器都说我错了。此外,此示例是 C++0x FCD(第 16.3.5/5 节)中一个更大示例的一部分,它也表示预期的替换是 x[0]

为什么重新扫描时没有替换x

C99 和 C++0x 实际上与引用部分中的 C++03 具有相同的措辞。

最佳答案

我相信你已经引用了关键段落,你只是停得太早了。 16.3.4/2(强调我的):

If the name of the macro being replaced is found during this scan of the replacement list (not including the rest of the source file’s preprocessing tokens), it is not replaced. Further, if any nested replacements encounter the name of the macro being replaced, it is not replaced. These nonreplaced macro name preprocessing tokens are no longer available for further replacement even if they are later (re)examined in contexts in which that macro name preprocessing token would otherwise have been replaced.

所以,在y的参数替换过程中,当xx[0]替换时,就是完全宏替换了,也就是说它在该点被重新扫描,并且 x 被递归规则捕获。这意味着 x[0] 中的 x 不再符合进一步替换的条件,包括在重新扫描 y(x) 的部分扩展结果期间.

关于c++ - 为什么在重新扫描期间没有替换参数替换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2949587/

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