为了账号安全,请及时绑定邮箱和手机立即绑定

C ++宏的可选参数

C ++宏的可选参数

C++
跃然一笑 2019-11-08 10:45:07
有什么方法可以通过C ++宏获取可选参数?某种重载也是很好的。
查看完整描述

3 回答

?
哈士奇WWW

TA贡献1799条经验 获得超6个赞

这是一种方法。它两次使用参数列表,首先形成助手宏的名称,然后将参数传递给该助手宏。它使用标准技巧来计算宏参数的数量。


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;

}

这使宏的调用者(而不是写者)更容易。


查看完整回答
反对 回复 2019-11-08
  • 3 回答
  • 0 关注
  • 715 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信