请注意,如果您创建了一个类,您可以根据需要构建任意数量的类型的消息,这意味着您可以与运算符或printf(3C)中的格式具有类似的效果。事情是这样的:
// make sure log remains copyable
class log
{
public:
log(const char *function, const char *filename, int line)
{
f_message << function << ":" << filename << ":" << line << ": ";
}
~log()
{
//printf("%s\n", f_message.str().c_str()); -- printf?!
std::cerr << f_message.str() << std::endl;
}
log& operator() (const char *value)
{
f_message << value;
}
log& operator() (int value)
{
f_message << value;
}
// repeat with all the types you want to support in the base class
// (should be all the basic types at least)
private:
sstream f_message;
};
// start the magic here
log log_error(const char *func, const char *file, int line)
{
log l(func, file, line);
return l;
}
// NOTE: No ';' at the end here!
#define LOG_DEBUG log_error(__func__, __FILE__, __LINE__)
// usage sample:
LOG_DEBUG("found ")(count)(" items");
需要注意的是,你可以声明< <运营商,而不是()。在这种情况下,结果使用情况如下:
LOG_DEBUG << "found " << count << " items";
取决于您更喜欢使用哪种方式。我喜欢(),因为它会自动保护你的表情。也就是说,如果你想输出“算< < 3”,那么你就必须写:
LOG_DEBUG << "found " << (count << 3) << " items";
不幸的是,这不允许像'DBG_WHEREAMI(“错误代码%d”,的errorCode)'。它不能工作,或者(至少不能移植),因为C++没有(还)有可变宏。 – 2010-07-10 03:22:20
不完全... 我想知道如果我可以在编译时生成一个包含__func__的字符串,这是运行时常量。 这似乎是不可能的。 – bbb 2010-07-12 09:50:11
@bbb:它是'static const',它在运行时没有机会被生成。 – 2013-02-02 05:08:07