类型重载宏 [英] Type overloading macro
问题描述
我有一堆printf调试助手宏,不必指定类型会很酷,是否可以做一些允许在c中进行宏重载的事情(如果gcc中有gcc的话,可以是gcc特定的) 4.3).我以为也许是typeof,但显然那是行不通的.
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 in c(can be gcc specific if its available in gcc 4.3). I thought maybe typeof but apparently that doesn't work.
example宏(我还有一些我不记得的ascii终端颜色东西)
example macro(I also have some ascii terminal color stuff that I can't remember of the top of my head)
#ifdef _DEBUG
#define DPRINT_INT(x) printf("int %s is equal to %i at line %i",#x,x,__LINE__);
.
.
.
#else
#define DPRINT_INT(x)
.
.
.
#endif
推荐答案
尝试一下;它使用gcc的__builtin方法,并尽最大可能自动为您确定类型,并在不需要指定类型的情况下提供了易于使用的DEBUG宏.当然,您可以将typeof(x)比较为float等.
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"); \
})
这篇关于类型重载宏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!