[英]C - Method overloading with different struct type arguments using macro
[英]Type overloading macro
我有一堆printf調試助手宏,如果不指定類型那將是非常酷的,你可以做些什么來允許c中的宏重載(如果它在gcc 4.3中可用,則可以是gcc特定的)。 我想也許是打字,但顯然這不起作用。
示例宏(我也有一些ascii終端顏色的東西,我不記得我的頭頂)
#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等進行比較等。
#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"); \
})
以下宏怎么樣? 它仍然需要您選擇打印格式,但您不必重新定義所有可能的情況,它也適用於MSVC:
#define DPRINT(t,v) printf("The variable '%s' is equal to '%" ## #t ## "' on line %d.\n",#v,v, __LINE__)
要使用它:
int var = 5;
const char *str = "test";
DPRINT(i,var);
DPRINT(s,str);
我想你可以試試下面的代碼:
#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) );
}
注意:DPRINT用法在此處使用雙括號。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.