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
?
Simple as:
#define EXPAND(x) x
#define GET_MACRO(_1, _2, _3, name, ...) name
#define FOO(...) EXPAND( GET_MACRO(__VA_ARGS__, FOO3, FOO2)(__VA_ARGS__) )
With the above definitions the "overloaded" FOO
macro expands like this:
FOO(a, b) // expands to FOO2(a, b)
FOO(a, b, c) // expands to FOO3(a, b, c)