使用__VA_ARGS__转换在MACRO中传递的所有参数

时间:2012-08-12 07:50:29

标签: c c-preprocessor variadic-macros

我有一个宏FOO(...),它接收到未知数​​量的参数。我想把所有这些参数都用于uint。有没有办法实现它?

1 个答案:

答案 0 :(得分:12)

是的,使用这些实用程序宏可以为每个参数应用一个宏(对于这些参数最多可以为8,但是可以扩展它们以获得更多):

/* This counts the number of args */
#define NARGS_SEQ(_1,_2,_3,_4,_5,_6,_7,_8,N,...) N
#define NARGS(...) NARGS_SEQ(__VA_ARGS__, 8, 7, 6, 5, 4, 3, 2, 1)

/* This will let macros expand before concating them */
#define PRIMITIVE_CAT(x, y) x ## y
#define CAT(x, y) PRIMITIVE_CAT(x, y)

/* This will call a macro on each argument passed in */
#define APPLY(macro, ...) CAT(APPLY_, NARGS(__VA_ARGS__))(macro, __VA_ARGS__)
#define APPLY_1(m, x1) m(x1)
#define APPLY_2(m, x1, x2) m(x1), m(x2)
#define APPLY_3(m, x1, x2, x3) m(x1), m(x2), m(x3)
#define APPLY_4(m, x1, x2, x3, x4) m(x1), m(x2), m(x3), m(x4)
#define APPLY_5(m, x1, x2, x3, x4, x5) m(x1), m(x2), m(x3), m(x4), m(x5)
#define APPLY_6(m, x1, x2, x3, x4, x5, x6) m(x1), m(x2), m(x3), m(x4), m(x5), m(x6)
#define APPLY_7(m, x1, x2, x3, x4, x5, x6, x7) m(x1), m(x2), m(x3), m(x4), m(x5), m(x6), m(x7)
#define APPLY_8(m, x1, x2, x3, x4, x5, x6, x7, x8) m(x1), m(x2), m(x3), m(x4), m(x5), m(x6), m(x7), m(x8)

所以现在你的FOO宏可以像这样定义:

#define FOO_EACH(x) (uint) x
#define FOO(...) APPLY(FOO_EACH, __VA_ARGS__)

导致:

FOO(x, y) // Expands to (uint) x, (uint) y