ostream C ++运算符的延迟评估 [英] Lazy evaluation with ostream C++ operators

查看:143
本文介绍了ostream C ++运算符的延迟评估的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种可移植的方式来在C ++中实现日志类的延迟评估。
假设我有一个简单的记录函数,如

I am looking for a portable way to implement lazy evaluation in C++ for logging class. Let's say that I have a simple logging function like

void syslog(int priority, const char *format, ...);

那么在syslog()函数中我们可以这样做:

then in syslog() function we can do:

if (priority < current_priority)
  return;

所以我们从来没有真正调用格式化函数(sprintf)。
另一方面,如果我们使用像

so we never actually call the formatting function (sprintf). On the other hand, if we use logging stream like

log << LOG_NOTICE << "test " << 123;

所有的格式化总是执行,这可能需要很多时间。
有可能实际使用ostream的所有好处(如自定义<<<<类,安全,优雅的语法的运算符...),在执行日志级别检查后执行formating ?

all the formating is always executed, which may take a lot of time. Is there any possibility to actually use all the goodies of ostream (like custom << operator for classes, type safety, elegant syntax...) in a way that the formating is executed AFTER the logging level is checked ?

推荐答案

我在我们的应用程序中做的是返回一个 boost :: iostreams :: null_stream 在日志记录级别过滤该语句的情况下。这工作得相当好,但仍然会调用所有<

What I've done in our apps is to return a boost::iostreams::null_stream in the case where the logging level filters that statement. That works reasonably well, but will still call all << operators.

如果日志级别是在编译时设置的,则可以切换到一个null<<

If the log level is set at compile time, you could switch to an object with a null << operator.

否则,它是Jerry说的表达式模板。

Otherwise, it's expression templates as Jerry said.

这篇关于ostream C ++运算符的延迟评估的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆