Overloading Macro on Number of Arguments

后端 未结 8 1573
离开以前
离开以前 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:55

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

    #define _my_BUGFX(x) x
    
    #define _my_NARG2(...) _my_BUGFX(_my_NARG1(__VA_ARGS__,_my_RSEQN()))
    #define _my_NARG1(...) _my_BUGFX(_my_ARGSN(__VA_ARGS__))
    #define _my_ARGSN(_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,N,...) N
    #define _my_RSEQN() 10,9,8,7,6,5,4,3,2,1,0
    
    #define _my_FUNC2(name,n) name ## n
    #define _my_FUNC1(name,n) _my_FUNC2(name,n)
    #define GET_MACRO(func,...) _my_FUNC1(func,_my_BUGFX(_my_NARG2(__VA_ARGS__))) (__VA_ARGS__)
    
    #define FOO(...) GET_MACRO(FOO,__VA_ARGS__)
    

提交回复
热议问题