使用__VA_ARGS__转换在MACRO中传递的所有参数 [英] Casting all parameters passed in MACRO using __VA_ARGS__

查看:104
本文介绍了使用__VA_ARGS__转换在MACRO中传递的所有参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个宏FOO(...),它接收未知数量的参数.我想将所有这些参数转换为uint.有办法实现吗?

I have a macro FOO(...) that receives an unknown number of parameters. I want to cast all those params to uint. Is there a way to achieve it?

推荐答案

是的,使用这些实用程序宏,您可以将宏应用于每个参数(这些参数最多可以使用8个,但可以扩展为更多):

Yes, using these utility macros you can apply a macro to each argument(up to 8 for these but they could be expanded for more):

/* 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宏可以这样定义:

So now your FOO macro could be defined like this:

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

结果:

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

这篇关于使用__VA_ARGS__转换在MACRO中传递的所有参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆