这是一个替代方案,它使用编译器的死代码删除:
#define DEBUG(msg) if (!DEBUG_ENABLED) {} \
else dbglog() << __FILE__ << ":" << __LINE__ << " " << msg
#ifdef DEBUG_FLAG
#define DEBUG_ENABLED 1
#else
#define DEBUG_ENABLED 0
#endif
该dbglog
实例是一个ostream
包装器,用于检测日志行是否以换行符结尾。如果没有,它会增加一个。
struct dbglog {
std::ostream &os_;
mutable bool has_endl_;
dbglog (std::ostream &os = std::cerr) : os_(os), has_endl_(false) {}
~dbglog () { if (!has_endl_) os_ << std::endl; }
template <typename T> static bool has_endl (const T &) { return false; }
static bool has_endl (char c) { return (c == '\n'); }
static bool has_endl (std::string s) { return has_endl(*s.rbegin()); }
static bool has_endl (const char *s) { return has_endl(std::string(s)); }
template <typename T>
static bool same_manip (T & (*m)(T &), T & (*e)(T &)) { return (m == e); }
const dbglog & operator << (std::ostream & (*m)(std::ostream &)) const {
has_endl_ = same_manip(m, std::endl);
os_ << m;
return *this;
}
template <typename T>
const dbglog & operator << (const T &v) const {
has_endl_ = has_endl(v);
os_ << v;
return *this;
}
};
现在,您可以像这样添加一条简单的消息(注意,换行符是可选的):
DEBUG("A simple message");
DEBUG("A simple message with newline\n");
DEBUG("A simple message with endl") << std::endl;
或者,如果您想添加更多调试信息:
DEBUG("Entering: ") << __func__ << ", argc=" << argc << ", argv=" << argv;
//...
DEBUG("Leaving: ") << __func__ << std::endl;