C预处理程序替换多个参数

时间:2018-11-24 15:29:03

标签: c-preprocessor

我希望将FUNC(x1, x2, x3, etc..)替换为

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

我尝试过但因可变参数而失败。 FUNCFUNC2都必须是宏。

1 个答案:

答案 0 :(得分:1)

这是可行的,但并非无关紧要。

我为此使用了BX_foreach(Joiner,Function,...)宏,实现如下 (为大约8个参数生成-您应该能够弄清楚如何生成更多参数):

#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)