C-可变参数宏,它扩展为每个参数上的一组宏调用 [英] C - Variadic macro which expands into set of macro calls on each argument
问题描述
我想要一个带有多个函数指针的宏调用,并且每个函数指针都由第二个宏调用,这是一个函数声明.
I want to have a single macro call which takes in multiple function pointers, and each function pointer is called by a second macro which is a function declaration.
我想要表格上的两个宏
#define FUNCTION_DEF(func) extern int func(void);
#define FUNCTION_DEFS(...) (???)
如此称呼
FUNCTION_DEFS(
myFunc1,
myFunc2,
otherFunc1,
otherFunc2,
defaultFunc
)
扩展为
FUNCTION_DEF(myFunc1)
FUNCTION_DEF(myFunc2)
FUNCTION_DEF(otherFunc1)
FUNCTION_DEF(otherFunc2)
FUNCTION_DEF(defaultFunc)
换句话说,对FUNCTION_DEFS
的单次调用扩展为所有可变参数的函数声明.
In other words, this single call to FUNCTION_DEFS
expands into function declarations of all the variadic arguments.
当前,我只是跳过第一步,并在每个函数指针上调用FUNCTION_DEF
,但是对此的解决方案将是不错的.
Currently I'm just skipping the first step and calling FUNCTION_DEF
on each function pointer, however a solution to this would be great.
这可能吗?
感谢@Vality将我介绍给X-Macro.我发现这篇文章"在现实世界中使用X-Macros "正是我所需要的.
Thanks to @Vality for introducing me to X-Macro. I found this post "Real-world use of X-Macros" which was exactly what I needed.
推荐答案
我不相信使用标准C预处理程序可以实现您想要的精确功能.但是,使用X宏可以实现类似的解决方案.
I do not believe what you want precisely is possible using the standard C preprocessor. However a similar solution can be accomplished with X macros.
要使用它们等效于您的代码,您首先需要将函数列表定义为X宏:
To do the equivalent of your code using them you would first define the function list as an X macro:
#define FUNCTION_LIST_A \
X(myFunc1) \
X(myFunc2) \
X(otherFunc1) \
X(otherFunc2) \
X(defaultFunc)
然后使用特定的宏实例化这些功能,然后定义要在每个功能上执行的宏:
Then to instantiate these functions with a specific macro you would then define the macro to perform on each function:
#define X(name) FUNCTION_DEF(name)
FUNCTION_LIST_A
#undef X
然后将其扩展为:
FUNCTION_DEF(myFunc1)
FUNCTION_DEF(myFunc2)
FUNCTION_DEF(otherFunc1)
FUNCTION_DEF(otherFunc2)
FUNCTION_DEF(defaultFunc)
希望这是有用的并且接近您想要的.诚然,语法有很大不同,但是如果您要完成的工作是将选定的函数或宏应用于整个数据列表(在这种情况下为函数指针),这是我所知使用c预处理器的最惯用的方式
Hopefully this is useful and close to what you want. Admittedly the syntax is significantly different but if what you wish to accomplish is to apply a chosen function or macro to a whole list of data (in this case function pointers) this is the most idiomatic way I know of to do so using the c preprocessor.
这篇关于C-可变参数宏,它扩展为每个参数上的一组宏调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!