如果您愿意使用稍微笨拙的语法,那么您可以使用 Boost.Preprocessor 的序列:
#include <boost/preprocessor.hpp>
#define G(args) BOOST_PP_SEQ_FOR_EACH_I(G_GENF, x, args)
#define G_GENF(r, data, i, elem) \
BOOST_PP_COMMA_IF(BOOST_PP_NOT_EQUAL(i, 0)) f(elem)
用法:
G((a))
G((b)(c))
G((d)(e)(f))
结果:
f(a)
f(b) , f(c)
f(d) , f(e) , f(f)
如果您确实需要G(a, b, c)
语法,那么由于宏替换不是递归的,我认为您可能需要每个要传递的参数数量一个宏。不过,您仍然可以从源中其他地方使用的单个宏委托给这些宏。考虑:
// Utility for counting the number of args in the __VA_ARGS__ pack:
#define PP_NARGS(...) PP_NARGS2(__VA_ARGS__, PP_NARGS_COUNT())
#define PP_NARGS2(...) PP_NARGS_IMPL(__VA_ARGS__)
#define PP_NARGS_IMPL(x1, x2, x3, N, ...) N
#define PP_NARGS_COUNT() 3, 2, 1, 0, ERROR
// Macros to delegate to concrete, defined-arity implementations:
#define XF(count, ...) XF_IMPL (count, __VA_ARGS__)
#define XF_IMPL(count, ...) XF_ ## count (__VA_ARGS__)
// Defined-arity implementations:
#define XF_1(x1) f(x1)
#define XF_2(x1, x2) f(x1), f(x2)
#define XF_3(x1, x2, x3) f(x1), f(x2), f(x3)
// Delegation macro; this is the only macro you need to call from elsewhere:
#define G(...) XF(PP_NARGS(__VA_ARGS__), __VA_ARGS__)
用法:
G(a)
G(b, c)
G(d, e, f)
结果:
f(a)
f(b), f(c)
f(d), f(e), f(f)
这当然可以进一步推广,一些预处理器实用程序库可能已经有一些工具可以做到这一点,但这展示了如何做到这一点。(我不熟悉任何 C99/C++0x 预处理器库,所以我不能推荐一个。)