gpt4 book ai didi

c++ - 如何根据预定义的宏(C++ 预处理器)组成有效的 token ?

转载 作者:行者123 更新时间:2023-11-28 00:30:18 26 4
gpt4 key购买 nike

假设某些标记 FOOBARDUD(可能还有更多)是否 #defined .我想要一个生成有效扩展名称的宏 EXTEND(name),例如

#define FOO
#undef BAR
#define DUD
EXTEND(object)

扩展为

object_foo_dud

如果有 n 个宏标记(如 FOOBARDUD)?我认为 O(n) 行应该是可能的,但是怎么做呢?

我已经试过了:

#ifdef FOO
# define ExtFOO(name) name ## _foo
#else
# define ExtFOO(name) name
#endif

#ifdef BAR
# define ExtBAR(name) ExtFOO(name) ## _bar
#else
# define ExtBAR(name) ExtFOO(name)
#endif

#ifdef DUD
# define ExtDUD(name) ExtBAR(name) ## _dud
#else
# define ExtDUD(name) ExtBAR(name)
#endif

#define EXTEND(name) ExtDUD(name)

但是

test.cc:26:5: error: pasting formed ')_dud', an invalid preprocessing token
EXTEND(object)
^

最佳答案

## 运算符连接两个预处理标记,并且必须产生一个单个 有效标记。例如,来自 C99 规范的第 6.10.3.3 节:

For both object-like and function-like macro invocations, before the replacement list is reexamined for more macro names to replace, each instance of a ## preprocessing token in the replacement list (not from an argument) is deleted and the preceding preprocessing token is concatenated with the following preprocessing token. Placemarker preprocessing tokens are handled specially: concatenation of two placemarkers results in a single placemarker preprocessing token, and concatenation of a placemarker with a non-placemarker preprocessing token results in the non-placemarker preprocessing token. If the result is not a valid preprocessing token, the behavior is undefined. The resulting token is available for further macro replacement. The order of evaluation of ## operators is unspecified.

所以扩展 ExtBAR(name) ## _dud 是无效的,因为它会产生 ExtBAR(object)_dud

我会采用以下方法:

#ifdef FOO
# define ValFOO _foo
#else
# define ValFOO
#endif

#ifdef BAR
# define ValBAR _bar
#else
# define ValBAR
#endif

#ifdef DUD
# define ValDUD _dud
#else
# define ValDUD
#endif

#define CONCAT(a, b, c, d) a ## b ## c ## d
#define XCONCAT(a, b, c, d) CONCAT(a, b, c, d)
#define EXTEND(name) XCONCAT(name, ValFOO, ValBAR, ValDUD)

需要中间的 XCONCAT 步骤,因为如果使用 ## 连接宏参数,则它们不会扩展。

关于c++ - 如何根据预定义的宏(C++ 预处理器)组成有效的 token ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23218925/

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