3 回答

TA貢獻(xiàn)1799條經(jīng)驗 獲得超6個贊
這是一種方法。它兩次使用參數(shù)列表,首先形成助手宏的名稱,然后將參數(shù)傳遞給該助手宏。它使用標(biāo)準(zhǔn)技巧來計算宏參數(shù)的數(shù)量。
enum
{
plain = 0,
bold = 1,
italic = 2
};
void PrintString(const char* message, int size, int style)
{
}
#define PRINT_STRING_1_ARGS(message) PrintString(message, 0, 0)
#define PRINT_STRING_2_ARGS(message, size) PrintString(message, size, 0)
#define PRINT_STRING_3_ARGS(message, size, style) PrintString(message, size, style)
#define GET_4TH_ARG(arg1, arg2, arg3, arg4, ...) arg4
#define PRINT_STRING_MACRO_CHOOSER(...) \
GET_4TH_ARG(__VA_ARGS__, PRINT_STRING_3_ARGS, \
PRINT_STRING_2_ARGS, PRINT_STRING_1_ARGS, )
#define PRINT_STRING(...) PRINT_STRING_MACRO_CHOOSER(__VA_ARGS__)(__VA_ARGS__)
int main(int argc, char * const argv[])
{
PRINT_STRING("Hello, World!");
PRINT_STRING("Hello, World!", 18);
PRINT_STRING("Hello, World!", 18, bold);
return 0;
}
這使宏的調(diào)用者(而不是寫者)更容易。
- 3 回答
- 0 關(guān)注
- 756 瀏覽
添加回答
舉報