在参数数量上重载宏 [英] Overloading Macro on Number of Arguments

查看:23
本文介绍了在参数数量上重载宏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个宏 FOO2FOO3:

#define FOO2(x,y) ...
#define FOO3(x,y,z) ...

我想定义一个新的宏 FOO 如下:

I want to define a new macro FOO as follows:

#define FOO(x,y) FOO2(x,y)
#define FOO(x,y,z) FOO3(x,y,z)

但这不起作用,因为宏不会在参数数量上超载.

But this doesn't work because macros do not overload on number of arguments.

不修改FOO2FOO3,有没有办法定义宏FOO(使用__VA_ARGS__或否则) 获得将 FOO(x,y) 分派到 FOO2FOO(x,y,z) 到 <代码>FOO3?

Without modifying FOO2 and FOO3, is there some way to define a macro FOO (using __VA_ARGS__ or otherwise) to get the same effect of dispatching FOO(x,y) to FOO2, and FOO(x,y,z) to FOO3?

推荐答案

简单如:

#define GET_MACRO(_1,_2,_3,NAME,...) NAME
#define FOO(...) GET_MACRO(__VA_ARGS__, FOO3, FOO2)(__VA_ARGS__)

如果你有这些宏:

FOO(World, !)         # expands to FOO2(World, !)
FOO(foo,bar,baz)      # expands to FOO3(foo,bar,baz)

如果你想要第四个:

#define GET_MACRO(_1,_2,_3,_4,NAME,...) NAME
#define FOO(...) GET_MACRO(__VA_ARGS__, FOO4, FOO3, FOO2)(__VA_ARGS__)

FOO(a,b,c,d)          # expeands to FOO4(a,b,c,d)

当然,如果您定义了 FOO2FOO3FOO4,输出将被定义的宏替换.

Naturally, if you define FOO2, FOO3 and FOO4, the output will be replaced by those of the defined macros.

这篇关于在参数数量上重载宏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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