Variadic macros with zero arguments

前端 未结 7 1237
失恋的感觉
失恋的感觉 2020-12-14 16:06

I am working on a call macro,

#define CALL(f,...) FN(f)->call((ref(new LinkedList()), __VA_ARGS__))

which when called,

C         


        
相关标签:
7条回答
  • 2020-12-14 16:34

    Simply make f part of the ..., and use a separate macro to extract the first argument where you need f.

    0 讨论(0)
  • 2020-12-14 16:35

    As for the updated question, by the use of auxiliary macro VA_ARGS like the following, the arguments will be expanded as expected.

    #define VA_ARGS(...) , ##__VA_ARGS__
    #define CALL(f,...) FN(f)->call((ref(new LinkedList()) VA_ARGS(__VA_ARGS__)))
    
    0 讨论(0)
  • 2020-12-14 16:47

    Unfortunately this cannot be done. You will need to define a separate macro to do this call.

    As you end up with invalid arguments when VA_ARGS is substituted with nothing you end up with a floating ,

    #define CALL0(f) FN(f)->call((ref(new LinkedList())))
    
    0 讨论(0)
  • 2020-12-14 16:48

    A common theme in these answers is that we need a GCC specific hack. One way is to use the token-paste ##__VAR_ARGS__, but pasted arguments are not macro expanded, which means that macros cannot be nested. But if you are going to do something GCC specific anyway, then why not use the old-fashioned GCC extension:

     #define VARARG_FOO(ZeroOrMoreArgs...) \
         printf("VARARG_FOO: " ZeroOrMoreArgs)
    

    ZeroOrMoreArgs is simply replaced by all the arguments (if any), commas and all. This includes recursive macro expansion.

    • then VARARG_FOO() expands to printf("VARARG_FOO: ")
    • and VARARG_FOO("I iz %d", 42) expands to printf("VARARGFOO: " "I iz %d", 42)

    Finally

     #define NEST_ME "I tawt I taw a puddy tat"
     VARARG_FOO("The evil one says %s", NEST_ME); 
    

    will expand to

     printf("VARARG_FOO: " "The evil one says %s", "I tawt I taw a puddy tat");
    

    Pros:

    • You can nest macro invocations, while having zero-or more aguments.

    Cons:

    • The ##__VA_ARGS__ hack might be harmless in standard C programs in the case where they always have at least one comma. (I haven't thought about whether this is true or not).
    • According to @ScootMoonen the ##__VA_ARGS__ hack is an undocumented extension to MSVC.
    0 讨论(0)
  • 2020-12-14 16:49

    __VA_OPT__ (c++2a) should be more reliable, eg: from http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0306r2.html

    The canonical use case of VA_OPT is for an optional separator:

    #define LOG(msg, ...) printf(msg __VA_OPT__(,) __VA_ARGS__)

    0 讨论(0)
  • 2020-12-14 16:53

    If you are using GCC, it has an extension to swallow up the comma preceding the __VA_ARGS__. See: http://gcc.gnu.org/onlinedocs/cpp/Variadic-Macros.html.

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