Type overloading macro

末鹿安然 提交于 2019-12-03 13:57:45

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");                        \

  })

How about the following macro? It still requires you to pick the print format but you won't have to redefine all possible cases and it works on MSVC as well:

#define DPRINT(t,v) printf("The variable '%s' is equal to '%" ## #t ## "' on line %d.\n",#v,v, __LINE__)

To use it:

int var = 5;
const char *str = "test";
DPRINT(i,var);
DPRINT(s,str);

I think you can give a try with following code:

#define DPRINT(fmt) do{ \
            my_printf fmt ; \
        } while(0)

my_printf( const char* szFormat, ... )
{
    char szDbgText[100];

    va_start(args, szFormat);
    vsnprintf(&szDbgText,99,szFormat,args);
    va_end(args);

    fprintf( stderr, "%s", szDbgText );
}
// usage
func( )
{
    int a = 5;
    char *ptr = "hello";

    DPRINT( ("a = %d, ptr = %s\n", a, ptr) );
}

Note: DPRINT usage takes dual parentheses here.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!