在函数中C++宏参数和默认参数

C++ macro and default arguments in function

本文关键字:参数 默认 C++ 函数      更新时间:2023-10-16

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

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

参数列表:

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

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

我开发了一些非常相似的东西 - Visual Studio的自定义警告生成器片段 - 使用宏。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)

我在这里做了一个详细的描述(警告:这是我的博客 - 所以认为它是一个无耻的插件)。