为什么这个嵌套宏替换失败? [英] Why is this nested macro replacement failing?
问题描述
我正在尝试应用 X Macro 概念,以便可以将所有结构成员初始化为自定义默认(无效)值.我写了以下代码:
I am trying to apply the X Macro concept, in order to have the possibility to initialize all struct members to a custom default (invalid) value. I write the following code:
#define LIST_OF_STRUCT_MEMBERS_foo
X(a)
X(b)
X(c)
#define X(name) int name;
struct foo {
LIST_OF_STRUCT_MEMBERS_foo
};
#undef X
#define X(name) -1,
static inline void foo_invalidate(struct foo* in) {
*in = (struct foo){
LIST_OF_STRUCT_MEMBERS_foo
};
}
#undef X
#define X(name) -1,
#define foo_DEFAULT_VALUE { LIST_OF_STRUCT_MEMBERS_foo }
#undef X
static struct foo test = foo_DEFAULT_VALUE;
但是,当我运行预处理器时,foo_DEFAULT_VALUE
的定义无法将 X(name)
调用替换为 -1,
However, when I run the preprocessor, the definition of foo_DEFAULT_VALUE
fails to substitute the X(name)
calls with -1,
预处理器输出:
struct foo {
int a; int b; int c;
};
static inline void foo_invalidate(struct foo* in) {
*in = (struct foo){
-1, -1, -1, /*Here the substitution worked nicely*/
};
}
static struct foo test = { X(a) X(b) X(c) }; /*Why this substitution failed?*/
我认为 C-macros 可以引用其他宏.你知道为什么替换失败吗?有什么解决办法吗?
I thought C-macros could refer to other macros. Do you know why that substitution fails? Is there any workaround?
我可以接受 foo_invalidate
,但我不愿意放弃在初始化时直接使用值的一步.
I could live with foo_invalidate
, but I am reluctant to give up one step from having a value to be used directly at initialization.
推荐答案
假设我们是预处理器,遇到了一行:
Let's pretend that we are the preprocessor and encountering the line:
static struct foo test = foo_DEFAULT_VALUE;
通过 1:
static struct foo test = { LIST_OF_STRUCT_MEMBERS_foo };
通过 2:
static struct foo test = { X(a) X(b) X(c) };
第 3 步:没有可扩展的内容,因为此行未定义 X
.
Pass 3: Nothing to expand as X
is undefined on this line.
一种解决方法是定义一个 const 变量(可能但不一定是 static
)用作默认值:
One workaround could be defining a const variable (possibly but not necessarily static
) to be used as default value:
#define X(name) -1,
static const struct foo foo_DEFAULT_VALUE = { LIST_OF_STRUCT_MEMBERS_foo };
#undef X
生成:
static const struct foo foo_DEFAULT_VALUE = { -1, -1, -1, };
这篇关于为什么这个嵌套宏替换失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!