Overloading Macro on Number of Arguments

后端 未结 8 1663
离开以前
离开以前 2020-11-22 04:25

I have two macros FOO2 and FOO3:

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

I want to define a new macro

8条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 05:00

    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:

    #define _ARG2(_0, _1, _2, ...) _2
    #define NARG2(...) _ARG2(__VA_ARGS__, 2, 1, 0)
    

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

    #define FOO1(a) a();
    #define FOO2(a,b) a(b);
    
    #define _ARG2(_0, _1, _2, ...) _2
    #define NARG2(...) _ARG2(__VA_ARGS__, 2, 1, 0)
    
    #define _ONE_OR_TWO_ARGS_1(a) FOO1(a)
    #define _ONE_OR_TWO_ARGS_2(a, b) FOO2(a,b)
    
    #define __ONE_OR_TWO_ARGS(N, ...) _ONE_OR_TWO_ARGS_ ## N (__VA_ARGS__)
    #define _ONE_OR_TWO_ARGS(N, ...) __ONE_OR_TWO_ARGS(N, __VA_ARGS__)
    
    #define FOO(...) _ONE_OR_TWO_ARGS(NARG2(__VA_ARGS__), __VA_ARGS__)
    

    So if you have

    FOO(a)
    FOO(a,b)
    

    The preprocessor expands that to

    a();
    a(b);
    

    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.

提交回复
热议问题