【发布时间】: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