是的你可以。以下支持最多 4 个参数,但可以轻松扩展以支持更多:
#define MACRO(api, ...) \
bool ret = api(__VA_ARGS__ VA_COMMA(__VA_ARGS__) 456)
/*
* VA_COMMA() expands to nothing if given no arguments and a comma if
* given 1 to 4 arguments. Bad things happen if given more than 4
* arguments. Don't do it.
*/
#define VA_COMMA(...) GET_6TH_ARG(,##__VA_ARGS__,COMMA,COMMA,COMMA,COMMA,)
#define GET_6TH_ARG(a1,a2,a3,a4,a5,a6,...) a6
#define COMMA ,
/* EXAMPLES */
MACRO(foo) /* bool ret = foo( 456) */
MACRO(foo,1) /* bool ret = foo(1 , 456) */
MACRO(foo,1,2,3,4) /* bool ret = foo(1,2,3,4 , 456) */
/* uh oh, too many arguments: */
MACRO(foo,1,2,3,4,5) /* bool ret = foo(1,2,3,4,5 5 456) */
MACRO(foo,1,2,3,4,5,6) /* bool ret = foo(1,2,3,4,5,6 5 456) */
同样的技巧用于:
解释
VA_COMMA
用六个附加参数包围它的参数 ( __VA_ARGS__
):一个空参数之前(不必为空 - 它被丢弃)和四个逗号和一个空参数之后。
这六个或更多参数被传递给GET_6TH_ARG
,顾名思义,它扩展到第六个参数。所有其他参数都被丢弃。
因此,MACRO(foo)
展开如下:
step 0: MACRO(foo)
step 1: bool ret = foo( VA_COMMA() 456)
step 2: bool ret = foo( GET_6TH_ARG(,COMMA,COMMA,COMMA,COMMA,) 456)
step 3: bool ret = foo( 456)
MACRO(foo,1)
展开如下:
step 0: MACRO(foo,1)
step 1: bool ret = foo(1 VA_COMMA(1) 456)
step 2: bool ret = foo(1 GET_6TH_ARG(,1,COMMA,COMMA,COMMA,COMMA,) 456)
step 3: bool ret = foo(1 COMMA 456)
step 4: bool ret = foo(1 , 456)
MACRO(foo,1,2)
展开如下:
step 0: MACRO(foo,1,2)
step 1: bool ret = foo(1,2 VA_COMMA(1,2) 456)
step 2: bool ret = foo(1,2 GET_6TH_ARG(,1,2,COMMA,COMMA,COMMA,COMMA,) 456)
step 3: bool ret = foo(1,2 COMMA 456)
step 4: bool ret = foo(1,2 , 456)
MACRO(foo,1,2,3,4,5)
展开如下:
step 0: MACRO(foo,1,2,3,4,5)
step 1: bool ret = foo(1,2,3,4,5 VA_COMMA(1,2,3,4,5) 456)
step 2: bool ret = foo(1,2,3,4,5 GET_6TH_ARG(,1,2,3,4,5,COMMA,COMMA,COMMA,COMMA,) 456)
step 3: bool ret = foo(1,2,3,4,5 5 456)