【问题标题】:How to bypass a << calling as if "#ifndef DEBUG" macro in c++?如何在 C++ 中绕过 << 调用,就像“#ifndef DEBUG”宏一样?
【发布时间】:2019-09-27 09:20:45
【问题描述】:

我为自己编写了一个小日志库,它接受两种形式的调用。

一个喜欢普通的函数调用,另一个喜欢 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 给出的解决方案。不同之处在于,mines 是 Logger_t 的friend-func,而 Botje's 是 member-func。 以下是我的:

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 仍然会产生调用二进制代码的函数,即使这些都是“无操作”调用。我不知道如何拆卸我的目标程序,所以我无法确认。

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

【问题讨论】:

  • 优化构建中(可能)不生成代码的解决方案是否正常?

标签: c++ macros iostream ostream conditional-compilation


【解决方案1】:

为什么不在非调试版本中将operator&lt;&lt; 设为无操作:

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

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

如果您还想避免 operator bool 定义为 Logger_t

#define log_debug false && Logger_t{}

【讨论】:

  • 感谢@Botje,我会试试你的第二种方法。
  • 我用你的方法得到了我想要的2!非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-10-05
  • 1970-01-01
  • 2011-02-27
  • 1970-01-01
  • 1970-01-01
  • 2013-01-16
  • 2017-12-30
相关资源
最近更新 更多