为 C++ 流创建宏

create macro for c++ stream

本文关键字:创建 C++      更新时间:2023-10-16

我正在编写一个宏,它将标准流作为参数。例如

文件.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++代码。

以下替代方案更有可能按预期工作;但是它也取决于LOG1LOG2到底是什么

#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函数与使用现代编译器的宏一样高效。由于其他原因,它们也更好。请参阅内联函数与预处理器宏。