Variable arguments inside a macro

后端 未结 3 1493
难免孤独
难免孤独 2021-01-27 08:17

I have two functions foo1(a,b) & foo2(a,b,c) and a macro

#define add(a,b) foo(a,b)

I need to re-define macro to accomplish,

1.if a

3条回答
  •  遥遥无期
    2021-01-27 09:16

    That usual trick for counting arguments may be adapted for this:

    #define ADD_EXPAND(...) \
            ADD_EXPAND_(__VA_ARGS__, EXPAND_ADD_FUNCS())
    
    #define ADD_EXPAND_(...) \
            EXPAND_ADD_SEL_FUNC(__VA_ARGS__)
    
    #define EXPAND_ADD_SEL_FUNC(first_, second_, third_, func, ...) func
    
    #define EXPAND_ADD_FUNCS() foo2, foo, dummy
    
    #define add(...) ADD_EXPAND(__VA_ARGS__)(__VA_ARGS__)
    

    Once you plow through the boiler plate, it basically just involves placing all the arguments in a line, with the function tokens after them, and seeing which function stands out. That's what EXPAND_ADD_SEL_FUNC does.

    You can see it live on coliru.

    But I'll reiterate what we told you in comments. This is likely to be a sub-par solution to a proper function. I haven't tested it thoroughly, so breakage is easily possible. Use at your own risk.

提交回复
热议问题