gpt4 book ai didi

c++ - 在 C++ 宏中输出反斜杠

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:28:25 25 4
gpt4 key购买 nike

是否可以在 C++ 中编写宏,AFTER 扩展将输出反斜杠符号?

现在我正在使用代码:

#define SOME_ENUM(XX) \
XX(FirstValue,) \
XX(SecondValue,) \
XX(SomeOtherValue,=50) \
XX(OneMoreValue,=100) \

但是我想写一个宏,它会生成上面的代码,所以我希望能够写:

ENUM_BEGIN(name) // it should output: #define SOME_ENUM(XX) \
ENUM(ONE) // it should output: XX(ONE,) \
//...

但我无法编写像 ENUM_BEGIN 这样的宏,因为它应该扩展为末尾带有反斜杠的内容。在 C++ 中可能吗?

最佳答案

不,这是不可能的。与此相关的是 ISO/IEC 14882:2011(E) 中描述的 §2.2.1,翻译阶段 2:

Each instance of a backslash character () immediately followed by a new-line character is deleted, splicing physical source lines to form logical source lines. Only the last backslash on any physical source line shall be eligible for being part of such a splice. If, as a result, a character sequence that matches the syntax of a universal-character-name is produced, the behavior is undefined. A source file that is not empty and that does not end in a new-line character, or that ends in a new-line character immediately preceded by a backslash character before any such splicing takes place, shall be processed as if an additional new-line character were appended to the file.

基本上会发生的是 \\\n(其中 \n 实际上在源代码中,而不是转义),将被视为 \ 字符,后跟一个行拼接。剩余的 \ 很可能会导致语法错误(可能有合法的情况,但我目前没有看到),并且在后续翻译阶段不会被视为行拼接(线路拼接仅发生在阶段#2)。

关于c++ - 在 C++ 宏中输出反斜杠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15645170/

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