C ++中的短路`运算符<<`输出 [英] Short circuit `operator<<` output in C++
问题描述
if(debug){
Output< < f1:<< f1()<< \\\
;
}
现在我想做的是写一个流类 Debug
其中我可以这样写
Debug< f1:<< f1()<< \\\
;
如果设置了一些全局标志,那么这将产生输出,否则。
现在:通过 Debug
可以很容易地返回一个流到 / dev / null
这将吞噬输出。问题是, f1()
仍然被评估(和'rendered'成一个文本表示,甚至可能更昂贵),这可能是相当糟糕的性能。 p>
现在我的问题:是否有任何技巧允许跳过
的'评估' f1:< f1()<< \\\
完全如果调试
决定不应该进行输出?类似于C ++为 f()&&& g()
其中 g()
c $ c> false (我认真考虑编写一个使用&&
作为输出运算符的流类,没有为过载的操作符和&&&
)执行循环。
你可以做的是定义这个宏:
#define Debug_Stream \
if else output
这将使得:
Debug_Stream<< f1:<< f1()<< \\\
;
变成等价的:
if(debug){
输出<< f1:<< f1()<< \\\
;
}
但实际上(加上可读性的空格)
if(!debug);
else
输出<< f1:<< f1()<< \\\
;
I have some code that is sprinkled with constructs like this
if(debug) {
Output << "f1: " << f1() << "\n";
}
Now what I want to do is write a stream class Debug
where I could write it like this
Debug << "f1: " << f1() << "\n";
If some global flag is set then this would generate output, otherwise not.
Now: this can be quite easily done by making Debug
return a stream that goes to /dev/null
which would swallow the output. The problem is that f1()
still gets evaluated (and 'rendered' into a textual representation which might be even more expensive) which might be quite bad for the performance.
Now my question: is there any trick that allows the skipping of the 'evaluation' of
"f1: " << f1() << "\n"
completely if Debug
decides that no output should be done? Similar to the short circuiting that C++ does for f() && g()
where g()
is not evaluated if f()
is false
(I seriously considered writing a stream class that uses &&
as the output operator but from what I read short-circuiting is not done for overloaded operator&&
)
What you can do is define this macro:
#define Debug_Stream \
if(!debug); else Output
This would make this:
Debug_Stream << "f1: " << f1() << "\n";
become equivalent to this:
if(debug) {
Output << "f1: " << f1() << "\n";
}
But literally (plus whitespace for readability)
if(!debug);
else
Output << "f1: " << f1() << "\n";
这篇关于C ++中的短路`运算符<<`输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!