C++ 宏的可选参数 [英] Optional Parameters with C++ Macros

查看:28
本文介绍了C++ 宏的可选参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法通过 C++ 宏获取可选参数?某种重载也不错.

Is there some way of getting optional parameters with C++ Macros? Some sort of overloading would be nice too.

推荐答案

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

Here's one way to do it. It uses the list of arguments twice, first to form the name of the helper macro, and then to pass the arguments to that helper macro. It uses a standard trick to count the number of arguments to a macro.

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;
}

这使宏的调用者更容易,但编写者却不是.

This makes it easier for the caller of the macro, but not the writer.

这篇关于C++ 宏的可选参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆