C预处理器替换多个参数



我想用替换FUNC(x1, x2, x3, etc..)

FUNC2(x1);
FUNC2(x2);
FUNC2(x3);
etc..

我尝试过varargs,但失败了。FUNCFUNC2都必须是宏。

这是可行的,但并非微不足道。

我使用BX_foreach(Joiner,Function,...)宏实现如下(为大约8个参数生成——您应该能够找出如何为更多参数生成它(:

#define BX_foreach(Join,What, ...) BX_foreach_(BX_argc(__VA_ARGS__), Join, What, __VA_ARGS__)
#define BX_foreach_(N, Join, What, ...) BX_paste(BX_cat(BX_foreach_, N)(Join, What, __VA_ARGS__))
#define BX_cat(X,Y)  BX_cat_(X,Y) //{{{
#define BX_cat_(X,Y) X##Y //}}}
#define BX_call_first(Fn,...) Fn ( __VA_ARGS__ )
#define BX_paste(...) __VA_ARGS__
#define BX_argc(...) BX_argc_(X,__VA_ARGS__) //{{{
#define BX_argc_(...) BX_argc__(,__VA_ARGS__,8,7,6,5,4,3,2,1,0,0)
#define BX_argc__(_,_0,_1,_2,_3,_4,_5,_6,_7,_8,Cnt,...) Cnt //}}}
#define BX_foreach_1(Join, What,  x) BX_call_first(What,  x)
#define BX_foreach_2(Join, What,  x,...)BX_call_first(What,x) Join BX_foreach_1(Join, What,  __VA_ARGS__)
#define BX_foreach_3(Join, What,  x,...)BX_call_first(What,x) Join BX_foreach_2(Join, What,  __VA_ARGS__)
#define BX_foreach_4(Join, What,  x,...)BX_call_first(What,x) Join BX_foreach_3(Join, What,  __VA_ARGS__)
#define BX_foreach_5(Join, What,  x,...)BX_call_first(What,x) Join BX_foreach_4(Join, What,  __VA_ARGS__)
#define BX_foreach_6(Join, What,  x,...)BX_call_first(What,x) Join BX_foreach_5(Join, What,  __VA_ARGS__)
#define BX_foreach_7(Join, What,  x,...)BX_call_first(What,x) Join BX_foreach_6(Join, What,  __VA_ARGS__)

有了它,你可以做:

#define FUNC(X) foo(X)
BX_foreach(;,FUNC,x1,x2,x3)

并将其扩展到

foo(x1) ; foo(x2) ; foo(x3)

最新更新