Variadic macro and trailing comma

后端 未结 2 1691
后悔当初
后悔当初 2021-01-02 09:45

I am trying to do object-orientation in C and want to have a syntactic sugar macro for the notation

object->vtable->method(object, arg1, arg2)
<         


        
相关标签:
2条回答
  • 2021-01-02 10:38

    In this answer there is technique explained which should allow you to count the number of parameters and use object and method as the first two arguments.

    0 讨论(0)
  • 2021-01-02 10:41

    Short answer, yes, it is possible in a portable way.

    Long answer: it's complicated, and you probably don't want to implement this yourself. There are ways to count the arguments that a macro receives and then take action according to that number. P99 implements a series of macros that can help you to achieve this. If you'd implement two base macros send_2 and send_more for the two cases you could then implement send as

    #define send(...)                     \
     P99_IF_LT(P99_NARG(__VA_ARGS__), 3)  \
     (send_2(__VA_ARGS__))                \
     (send_more(__VA_ARGS__))
    

    Technically these constructs in P99 have a restriction that they can't handle more than 150 (or so) arguments to send.

    BTW, you know that probably, calling a macro send is not really a good idea. Usually people prefer that macros are in all-caps. Also most of the time it is a good idea to have a name prefix that is unique to your library/package, such as AC245_SEND.

    0 讨论(0)
提交回复
热议问题