Type overloading macro

后端 未结 3 1158
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-15 23:04

I have a bunch of printf debug helper macros and it would be pretty cool to have to not specify the type, is there anything you can do to allow something like macro overloading

3条回答
  •  心在旅途
    2021-02-15 23:39

    Try this; it uses gcc's __builtin methods, and automatically determines the type for you, as best it can, and makes for an easy DEBUG macro where you don't have to specify the type. Of course, you can compare typeof (x) to float, etc. etc.

    #define DEBUG(x)                                                 \
      ({                                                             \
        if (__builtin_types_compatible_p (typeof (x), int))          \
            fprintf(stderr,"%d\n",x);                                \
        else if (__builtin_types_compatible_p (typeof (x), char))    \
            fprintf(stderr,"%c\n",x);                                \
        else if (__builtin_types_compatible_p (typeof (x), char[]))  \
            fprintf(stderr,"%s\n",x);                                \
        else                                                         \
            fprintf(stderr,"unknown type\n");                        \
    
      })
    

提交回复
热议问题