为 C++ 流创建宏
create macro for c++ stream
我正在编写一个宏,它将标准流作为参数。例如
文件.h
int enable = 0;
#define MYLOG(hanlde)
if (enable==0) { LOG1(handle) }
else { LOG2(handle) }
文件.cpp
MYLOG(handle) << "Test log msg";
预处理器执行后的预期结果必须是
LOG1(handle) << "Test log msg"; // if handle = 0
LOG2(handle) << "Test log msg"; // if handle = 1
这在 c++ 中的宏中是否可能。如果可能,请提供示例。
如前所述,您的 MYLOG 宏版本显然不会扩展到有效的C++代码。
以下替代方案更有可能按预期工作;但是它也取决于LOG1
和LOG2
到底是什么
#define MYLOG(handle) (enable == 0 ? LOG1(handle):LOG2(handle))
所示的宏将不起作用。您需要使用类似以下内容的内容:
#define MYLOG(hanlde)
(enable == 0 ? LOG1(handle) : LOG2(handle))
话虽如此,您可以使用同样有效的inline
函数。
inline std::ostream& MYLOG(handle_type handle)
{
return (enable == 0 ? LOG1(handle) : LOG2(handle))
}
简单的inline
函数与使用现代编译器的宏一样高效。由于其他原因,它们也更好。请参阅内联函数与预处理器宏。
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 使用std::multimap迭代器创建std::list
- 在全局变量中保存类的实例以重新创建类(创建"backup")
- 使用CMake创建QML插件
- 如何在c++中为模板函数实例创建快捷方式
- 在C++中,是否可以基于给定的标识符创建基类的新实例,反之亦然
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- OpenCV EqualizeHist()从彩色图像创建黑白图像
- 试图在visual studio上用C++创建一个桌面应用程序
- std::threads可以从Windows DLL中的全局变量创建/销毁吗?
- 如何在C++20中创建模板别名的推导指南
- 如何为模板化对象创建模板向量?VS正在投掷C3203
- 如何创建一个空的全局类并在启动时实例化它
- 无法创建抽象类的实例
- 链接到自行创建的dll失败
- 为什么我不能在不创建字符串变量的情况下使用函数的字符串输出
- 有没有一种方法可以创建一个带有哈希表的数据库,该哈希表具有恒定时间查找功能
- 如何在C++类内存结构中创建"spacer"?
- 终端不会为C++文件创建.exe文件吗
- 在createdialog创建的窗口中捕获用于编辑控件的OnMouseMove消息