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
?
Here's a spin off from Evgeni Sergeev's answer. This one supports zero argument overloads as well!
I tested this with GCC and MinGW. It ought to work with old and new versions of C++. Note that I wouldn't guarantee it for MSVC... But with some tweaking, I'm confident it could be made to work with that too.
I also formatted this to be pasted into a header file (which I called macroutil.h). If you do that, you can just include this header whatever you need the feature, and not look at the nastiness involved in the implementation.
Simple as:
So if you have these macros:
If you want a fourth one:
Naturally, if you define
FOO2
,FOO3
andFOO4
, the output will be replaced by those of the defined macros.Here is a more general solution:
Define your functions:
Now you can use
FOO
with 2, 3 and 4 arguments:Limitations
Ideas
Use it for default arguments:
Use it for functions with possible infinite number of arguments:
PS:
__NARG__
is copied from: https://groups.google.com/group/comp.std.c/browse_thread/thread/77ee8c8f92e4a3fb/346fc464319b1ee5?pli=1Maybe you can use this macro to count the number of arguments.
Here is a more compact version of the answer above. With example.
Run:
Note that having both
_OVR
and_OVR_EXPAND
may look redundant, but it's necessary for the preprocessor to expand the_COUNT_ARGS(__VA_ARGS__)
part, which otherwise is treated as a string.I was just researching this myself, and I came across this here. The author added default argument support for C functions via macros.
I'll try to briefly summarize the article. Basically, you need to define a macro that can count arguments. This macro will return 2, 1, 0, or whatever range of arguments it can support. Eg:
With this, you need to create another macro that takes a variable number of arguments, counts the arguments, and calls the appropriate macro. I've taken your example macro and combined it with the article's example. I have FOO1 call function a() and FOO2 call function a with argument b (obviously, I'm assuming C++ here, but you can change the macro to whatever).
So if you have
The preprocessor expands that to
I would definitely read the article that I linked. It's very informative and he mentions that NARG2 won't work on empty arguments. He follows this up here.