edv*_*dsp 5 c macros function-pointers variadic-macros
我想要一个接受多个函数指针的宏调用,并且每个函数指针由第二个宏调用,该宏是函数声明。
我想要表单上的两个宏
#define FUNCTION_DEF(func) extern int func(void);
#define FUNCTION_DEFS(...) (???)
Run Code Online (Sandbox Code Playgroud)
这就是所谓的
FUNCTION_DEFS(
myFunc1,
myFunc2,
otherFunc1,
otherFunc2,
defaultFunc
)
Run Code Online (Sandbox Code Playgroud)
扩展到
FUNCTION_DEF(myFunc1)
FUNCTION_DEF(myFunc2)
FUNCTION_DEF(otherFunc1)
FUNCTION_DEF(otherFunc2)
FUNCTION_DEF(defaultFunc)
Run Code Online (Sandbox Code Playgroud)
换句话说,这个单一调用FUNCTION_DEFS扩展到所有可变参数的函数声明。
目前,我只是跳过第一步并调用FUNCTION_DEF每个函数指针,但是对此的解决方案会很棒。
这可能吗?
感谢 @Vality 向我介绍 X-Macro。我发现这篇文章“ Real-world use of X-Macros ”正是我所需要的。
我不相信使用标准 C 预处理器可以实现您想要的精确结果。然而,可以使用 X 宏来完成类似的解决方案。
要使用它们执行与代码相同的操作,您首先需要将函数列表定义为 X 宏:
#define FUNCTION_LIST_A \
X(myFunc1) \
X(myFunc2) \
X(otherFunc1) \
X(otherFunc2) \
X(defaultFunc)
Run Code Online (Sandbox Code Playgroud)
然后,要使用特定宏实例化这些函数,您需要定义要在每个函数上执行的宏:
#define X(name) FUNCTION_DEF(name)
FUNCTION_LIST_A
#undef X
Run Code Online (Sandbox Code Playgroud)
然后将扩展为:
FUNCTION_DEF(myFunc1)
FUNCTION_DEF(myFunc2)
FUNCTION_DEF(otherFunc1)
FUNCTION_DEF(otherFunc2)
FUNCTION_DEF(defaultFunc)
Run Code Online (Sandbox Code Playgroud)
希望这有用并且接近您想要的。诚然,语法有很大不同,但如果您希望完成的是将选定的函数或宏应用于整个数据列表(在本例中为函数指针),这是我所知道的使用 c 预处理器执行此操作的最惯用的方法。