幾乎沒有C程序員利用#undef
的力量,特別是爲當前目的重新定義一個宏。這使您可以將所有數據設置爲一個可讀的表格,可以在1個位置進行更新和修改。
#define FUNCTION_MAP { \
MAP(ID_NOP_FUNCTION, NULL), \
MAP(ID_PRINT_FUNCTION, Print), \
MAP(ID_READ_FUNCTION, Read), \
MAP(ID_WRITE_FUNCTION, Write), \
MAP(ID_PROCESS_FUNCTION, Process), \
}
#define MAP(x,y) x
enum function_enums FUNCTION_MAP;
#undef MAP
#define MAP(x,y) y
Function_Ptr Export_Function_Table[] = FUNCTION_MAP;
#undef MAP
別急,還有更全部爲低,價格低$ 0與無標& H,你可以做你的函數頭魔神的全部1位。
#define FUNCTION_MAP \
/* ENUM Function, return, Arguments ... */ \
MAP(ID_PRINT_FUNCTION, Print, int, char *fmt, va_list *ap ) \
MAP(ID_READ_FUNCTION, Read, int, int fd, char *buf, size_t len) \
MAP(ID_WRITE_FUNCTION, Write, int, int fd, char *buf, size_t len) \
MAP(ID_PROCESS_FUNCTION, Process,int, int )
//function enums
#define MAP(x,y,...) x,
enum function_enums { FUNCTION_MAP };
#undef MAP
//function pre-definitions with unspecified number of args for function table
#define MAP(x,fn_name,ret,...) ret fn_name();
FUNCTION_MAP
#undef MAP
//function tables with unspecified number of arguments
#define MAP(x,y,...) y,
typedef int (*Function_Ptr)();
Function_Ptr Export_Function_Table[] = { FUNCTION_MAP };
#undef MAP
//function definitions with actual parameter types
#define MAP(x,fn_name,ret,...) ret fn_name(__VA_ARGS__);
FUNCTION_MAP
#undef MAP
//function strings ... just in case we want to print them
#define MAP(x,y,...) #y,
const char *function_strings[] = { FUNCTION_MAP };
#undef MAP
//function enum strings ... just in case we want to print them
#define MAP(x,y,...) #x,
const char *function_enum_strings[] = { FUNCTION_MAP };
#undef MAP
#undef FUNCTION_MAP
現在你可以就在這個頭的頂部添加每個新功能在一個地方,最好是如果你想保留向後兼容的庫FUNCTION_MAP結束......否則你可以只列出他們按字母順序排列。
問CW問題並不鼓勵人們迴應。 – 2010-05-12 21:12:04