在函数中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)
我在这里做了一个详细的描述(警告:这是我的博客 - 所以认为它是一个无耻的插件)。
相关文章:
- 使函数参数默认为周围范围
- 如何将值传递给其参数(默认参数)
- 当“std::make_index_sequence”和“std::index_sequence”用于模板参数默认类型时
- C ,构造器中允许的参考参数默认值
- 哪些规则控制参数默认赋值?
- 错误:上一个规范后给出的参数默认参数
- 是否可以设计一个包含模板参数默认值的类
- 构造函数中参数C++默认值
- 如何设置依赖于其他参数的参数默认值
- C++模板参数默认函数实现
- QInput对话框参数默认值
- g++4.8.2上列表方法参数默认初始化时出错
- 在函数定义中指定参数默认值会导致错误 C2143:语法错误:'='之前缺少')'
- 函数模板:将第一个模板参数默认为第二个
- 模板模板参数默认可以引用其他模板类型的参数
- 参数默认为先例参数的值
- 如何修改一个类,使它只有一个成员函数,所有参数默认
- 内置类型的模板参数默认值
- 是否可以使用构造函数或对象作为其他类方法的参数默认值?
- 模板参数默认为更高版本