Re:Pprint: Pretty Printer for Modern C++
by colejohnson66 on Monday April 29, 2019 @04:44PM
(#19782434)
Does anyone know why C++ uses the shift operator for streams? Itβs always rubbed me the wrong way
[ Parent
| on HN ]
Originally C++ lacked templates, and even once it got templates it was 20 (?) years before it got variadic templates. Operator overloads were added early, however, so using an operator for this was a "hack" to make a type safe print function. (It probably also served as a demo application for operator overloading.)
If you squint enough, it looks like a fluent interface, just fluent interfaces wouldn't become mainstream until later. That is, "cout << a << b << c;" is pretty close to "cout.print(a).print(b).print(c);"
Another reason to use an operator is that if you use free functions (without variadic parameters) then your parens and nesting stacks up: "print(print(print(cout, a), b), c);"
An infix operator doesn't have that problem.
In modern C++, there is at least the possibility to replace "<<" with something better for printing.
I mean, it's also looks intuitive. if you imagine the arrows as the data fllowing.
Re:Pprint: Pretty Printer for Modern C++
by mikepurvis on Monday April 29, 2019 @05:21PM
(#19782725)
Among its many flaws, you can't really use streams for output where internationalization will ever be a consideration, which immediately eliminates many potential use cases.
phaedrus explained why use an infix operator, but why specially the shift operator?
My guess: because it has very low precedence, allowing stuff like:
> cout << a + b * c << " is the result\n";
Instead of:
> cout << (a + b * c) << " is the result\n";
Re:Pprint: Pretty Printer for Modern C++
by JoeAltmaier on Monday April 29, 2019 @04:51PM
(#19782506)
Yes! They look cute, sure. But aren't they the wrong precedence? I think its because its a little-used operator that can be overloaded without interfering with normal expressions within the stream I/o invocation.