如何绕过 << 调用,就好像"#ifndef DEBUG" c++ 中的宏一样?

How to bypass a << calling as if "#ifndef DEBUG" macro in c++?

本文关键字:lt 一样 #ifndef 调用 何绕过 DEBUG c++      更新时间:2023-10-16

我为自己编写了一个小的logging-lib,它接受两种形式的调用。

一个喜欢正常的函数调用,另一个喜欢 std::ostream <<运算符输出。 然后,我为每个日志级别分别定义了几个宏,如下所示:

#ifdef DEBUG
#define LOG_DEBUG( strLogBody )  appendLog( leon_log::LogLevel_e::ellDebug,  std::string( __func__ ) + "()," + ( strLogBody ) )
#define LOG_INFOR( strLogBody ) appendLog( leon_log::LogLevel_e::ellInfor,  std::string( __func__ ) + "()," + ( strLogBody ) )
#define log_debug ( Logger_t( LogLevel_e::ellDebug ) << __func__ << "()," )
#define log_infor ( Logger_t( LogLevel_e::ellInfor ) << __func__ << "()," )
//...more for other log-levels
#else
#define LOG_DEBUG( strLogBody )
#define LOG_INFOR( strLogBody ) appendLog( leon_log::LogLevel_e::ellInfor, ( strLogBody ) )
#define log_debug ( Logger_t( LogLevel_e::ellDebug ) )
#define log_infor ( Logger_t( LogLevel_e::ellInfor ) )
//...more for other log-levels
#endif

当客户端代码空间中定义了"DEBUG"宏时,两者都会形成用于调试目的的产品目标代码。 当没有定义"DEBUG"宏时,前一种形式(如函数调用(不会产生任何二进制代码来加速我的应用程序(如我所愿(,而后者无论如何都会形成产品代码。

有没有办法,我可以绕过那些"<<"调用,就像绕过那些正常的函数调用一样?

到目前为止,我正在使用与@Botje给出的解决方案类似的解决方案。区别在于,矿山是Logger_t的朋友函件,而Botje是会员函件。 以下是我的:

template <typename T>
inline Logger_t& operator<<( Logger_t& lgr, const T& body ) {
if ( lgr.m_LogLevel >= g_ellLogLevel )
dynamic_cast<std::ostringstream&>( lgr ) << body;
return lgr;
};

但我想GCC仍然提供调用二进制代码的函数,即使这些都是"no-op"调用。我不知道如何拆卸我的目标程序,所以我无法确认。

谢谢!请原谅我丑陋的英语!

为什么不让operator<<在非调试版本中成为无操作:

#ifndef DEBUG
struct Logger_t {
template <class T>
Logger_t& operator <<(const T& o) { return *this; }
};
#endif

编译器应该能够将整个log_debug << ... << ...链减少到零。

如果还想避免在<<链中调用函数,请operator boolLogger_t

#define log_debug false && Logger_t{}