我为自己编写了一个日志记录库,它接受两种形式的调用。
一个喜欢普通的函数调用,另一个喜欢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”宏时,两者都形成用于DEBUGGING目的的产品目标代码。
当没有定义“ 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仍会产生调用二进制代码的函数。我不知道如何拆卸目标编,因此无法确认。
谢谢!请原谅我难看的英语!
最佳答案
为什么不在非调试版本中将operator<<
设为无操作:
#ifndef DEBUG
struct Logger_t {
template <class T>
Logger_t& operator <<(const T& o) { return *this; }
};
#endif
编译器应该能够将整个
log_debug << ... << ...
链减少为零。如果还要避免在
Logger_t
定义和#define log_debug false && Logger_t{}
关于c++ - 如何在C++中绕过<<调用,就像“#ifndef DEBUG”宏一样?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58131564/