Overloading Macro on Number of Arguments

2018-12-31 16:10发布

I have two macros FOO2 and FOO3:

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

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.

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?

8条回答
忆尘夕之涩
2楼-- · 2018-12-31 17:03

This seems to work fine on GCC, Clang and MSVC. It's a cleaned up version of some of the answers here

#define __BUGFX(x) x

#define __NARG2(...) __BUGFX(__NARG1(__VA_ARGS__,__RSEQN()))
#define __NARG1(...) __BUGFX(__ARGSN(__VA_ARGS__))
#define __ARGSN(_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,N,...) N
#define __RSEQN() 10,9,8,7,6,5,4,3,2,1,0

#define __FUNC2(name,n) name ## n
#define __FUNC1(name,n) __FUNC2(name,n)
#define GET_MACRO(func,...) __FUNC1(func,__BUGFX(__NARG2(__VA_ARGS__))) (__VA_ARGS__)
查看更多
其实,你不懂
3楼-- · 2018-12-31 17:08

To add on to netcoder's answer, you CAN in fact do this with a 0-argument macro, with the help of the GCC ##__VA_ARGS__ extension:

#define GET_MACRO(_0, _1, _2, NAME, ...) NAME
#define FOO(...) GET_MACRO(_0, ##__VA_ARGS__, FOO2, FOO1, FOO0)(__VA_ARGS__)
查看更多
登录 后发表回答