对参数的数目重载宏 [英] Overloading Macro on Number of Arguments

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

问题描述

我有两个宏 foo2的 FOO3

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

我要定义一个新宏 FOO 如下:

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

在不修改 foo2的 FOO3 ,是有一些方法来定义一个宏 FOO (使用 __ VA_ARGS __ 或以其他方式),以获得调度 FOO(X,Y) foo2的 FOO(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__)

所以,如果你有这些宏:

So if you have these macros:

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

如果你想有一个第四招:

If you want a fourth one:

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

当然,如果你定义 foo2的 FOO3 FOO4 ,输出将通过那些定义的宏来代替。

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

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

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