可变参数宏和尾部逗号 [英] Variadic macro and trailing comma
问题描述
我正在尝试在C语言中进行面向对象,并希望为该符号提供一个语法糖宏
I am trying to do object-orientation in C and want to have a syntactic sugar macro for the notation
object->vtable->method(object, arg1, arg2)
进入
send(object, method, arg1, arg2)
不幸的是,当方法不带参数时,会出现尾随逗号问题
Unfortunately when a method takes no argument, the trailing comma problem arises
send(object, method)
给予
object->vtable->method(object, )
是否有任何 便携式 (没有##__VA_ARGS__
或Visual Studio)这样做的方式?
Is there any portable (no ##__VA_ARGS__
or Visual Studio) way of doing this?
我想出了一个,但是我需要交换对象和方法
I figured out one but I need to swap the object and the method
#define FIRST_ARG_(N, ...) N
#define FIRST_ARG(args) FIRST_ARG_(args)
#define send(msg, ...) \
FIRST_ARG(__VA_ARGS__)->vtable->msg(__VA_ARGS__)
许可
send(method, object)
send(method, object, arg1, arg2)
修改
借助下面的两个很好的答案,我将使用这些宏进行处理.它最多可以处理16个参数,但可以轻松扩展
With the help of two good answers from below I will do it with these macros. It works up to 16 arguments but can easily be extended
#define SEND_NO_ARG(obj, msg) obj->vtable->msg(obj)
#define SEND_ARG(obj, msg, ...) obj->vtable->msg(obj, __VA_ARGS__)
#define GET_18TH_ARG(arg1, arg2, arg3, arg4, arg5, \
arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, \
arg16, arg17, arg18, ...) arg18
#define SEND_MACRO_CHOOSER(...) \
GET_18TH_ARG(__VA_ARGS__, \
SEND_ARG, SEND_ARG, SEND_ARG, SEND_ARG, SEND_ARG, \
SEND_ARG, SEND_ARG, SEND_ARG, SEND_ARG, SEND_ARG, \
SEND_ARG, SEND_ARG, SEND_ARG, SEND_ARG, SEND_ARG, \
SEND_NO_ARG, )
#define SEND(...) SEND_MACRO_CHOOSER(__VA_ARGS__)(__VA_ARGS__)
推荐答案
在此答案中,有技术说明了应允许您计算参数的数量,并使用object
和method
作为前两个参数.
In this answer there is technique explained which should allow you to count the number of parameters and use object
and method
as the first two arguments.
这篇关于可变参数宏和尾部逗号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!