【问题标题】:C++ macro and default arguments in function函数中的 C++ 宏和默认参数
【发布时间】:2012-05-14 11:32:52
【问题描述】:

我正在尝试创建一个通用函数来显示错误消息,并且程序可能会在消息显示后退出。

我希望函数显示发生错误的源文件和行。

参数列表:

1.char *desc //description of the error
2.char *file_name //source file from which the function has been called
3.u_int line //line at which the function has been called
4.bool bexit=false //true if the program should exit after displaying the error
5.int code=0 //exit code

由于 (4) 和 (5) 我需要在函数定义中使用默认参数,因为我不希望它们被指定,除非程序应该退出。

由于 (2) 和 (3),我需要使用一个重定向到原始函数的宏,例如:

#define Error(desc, ???) _Error(desc,__FILE,__LINE__, ???)

问题是我不明白这两个元素应该如何协同工作。

外观示例:

if(!RegisterClassEx(&wndcls))
    Error("Failed to register class",true,1); //displays the error and exits with exit code 1

if(!p)
    Error("Invalid pointer"); //displays the error and continues

【问题讨论】:

标签: c++ macros mingw default-arguments


【解决方案1】:

您不能在 C99 中重载宏——您需要两个不同的宏。对于 C11,使用 _Generic 有一些希望。

我使用宏开发了一些非常相似的东西——Visual Studio 的自定义警告生成器 sn-p。 GNU GCC 有一些与 MSVS 兼容的类似设置。

#define STR2(x) #x
#define STR1(x) STR2(x)
#define LOC __FILE__ “(“STR1(__LINE__)”) : Warning Msg: “
#define ERROR_BUILDER(x) printf(__FILE__ " (“STR1(__LINE__)”) : Error Msg: ” __FUNCTION__ ” requires ” #x)

以上行处理了您的参数 1 到 3。添加对 4 的支持需要在宏中插入 exit() 调用。此外,如果您需要两个不同的参数列表(具有默认参数的一个可以委托给另一个宏),请创建两个不同的宏包装器。

#define ERROR_AND_EXIT(msg, cond, errorcode) ERROR_BUILDER(msg) if (cond) exit(errorcode)
#define ERROR_AND_CONT(msg) ERROR_BUILDER(msg)

我已经提供了详细的描述here(警告:这是我的博客——所以认为它是一个无耻的插件)。

【讨论】:

    猜你喜欢
    • 2022-07-17
    • 1970-01-01
    • 1970-01-01
    • 2013-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-26
    相关资源
    最近更新 更多