繁体   English   中英

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

[英]C++ macro and default arguments in function

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

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

参数列表:

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)

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM