6 ms·
Basically, for human-readable output << is far inferior to the alternatives that came before it and after it, and from an API perspective has nasty warts both i
by dietrichepp 11y ago
Basically, for human-readable output << is far inferior to the alternatives that came before it and after it, and from an API perspective has nasty warts both in syntax and semantics.
* C's printf() is superior because it can be localized.
* Later formatting functions like Python's .format(), C# String.Format(), and C++ fmt::format() (from cppformat library) are far superior in normal use cases: they can be localized but they don't suffer from printf() safety problems.
* << suffers from severe problems in terms of syntax because it sits between arithmetic and comparison operators in precedence. So you can std::cout << x * 5; but you cannot std::cout << x & 0xff;
* iostream also suffers from the curse of statefulness. Unlike other formatting functions, changing the precision you want to use changes the properties of the IO stream itself, which is nonsensical. Either the properties should be bundled with the number or they should be lexically scoped.
Maybe << is nice for one or two things, but for the bread and butter of what developers do, it's absolutely terrible. I don't know how it makes "streaming nicer" because I'm not sure what you mean by streaming—the word has a few different possible contextual meanings, and I can't imagine how << makes any of those any easier.
The worst part of this is that they could have just used function call syntax and two of the major usability problems would have instantly disappeared. It would avoid problems with precedence and it would allow you to pass additional precision parameters.
Unfortunately, localization is really a hard (as in non-negotiable) requirement, and since << is so terrible at it, you are often forced to rip its usage out of a program rather than just work around it.
- blub 11y agoSure, << has these problems and for more advanced use cases one can use Boost or the library you mentioned. For localization one has to use a non-STL solution anyway, because the supporty is rudimentary in the standard lib. On the other hand, there's nothing easier than using << for logging and concatenating + optionally converting strings and other types. All in all the only real problem caused by << being an operator instead of a function is the precedence one; the rest are API design issues I would argue. Luckily it's a compiler warning (unused value) and if one adds another output op to the chain it will most likely be a compile error or still a warnig. So I still don't see why we have to condemn operator overloading because of <<.