Overloading Macro on Number of Arguments

后端 未结 8 1693
离开以前
离开以前 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 04:54

    Simple as:

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

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

提交回复
热议问题