overloading operators for I/O

Michiel nomail at hotmail.com
Wed Feb 14 13:49:06 PST 2007


> Good question. C++ conventional wisdom is that's great, because it's
> always been done that way in C++. Few question it.

Sure. I can't deny that I'm used to it because of C++.

> Let's step back a bit.
>
> <nuclear missile example>

+ is intuitively addition because it's been that way in mathematics long before
there were ever computers. Bitshifts, on the other hand, are a bit more recent.
And using the << operator for them even more so.

It might have been the << operator's first use, but not necessarily its best. <<
is an arrow. When you point an arrow from a to b, I assume that either a is going
to b, or that a becomes b. Not that a is shifted right by b bits.

> So why overload operators at all? For the purposes of implementing UDTs
> (User Defined Types) that have legitimate arithmetic operations on them,
> such as matrices, extended precision numbers, etc.

I totally agree with you here. For example, the way you implemented the
equality/inequality and comparison operators is great. Much less room for misuse.

And in C++, I never deviated from that behavior.

>
> <some more examples>
>

Some good points (though you were using C++ templates as an example, not D
templates). But I could make the same argument for writefln:

writefln(add(5, 7, 8, pow(42, 3)), f("one", "two", "three, four"));

That's not very clear to me either. People will just have to make their own code a
bit nicer and use proper spacing or what have you.

> And to sum up:
>
>  writefln(a, b, c, d);
>
> seems pretty intuitive to me. There's just no advantage to overloading <<.

What about the other reason I mentioned? About sending messages to abstract
objects with a standard operator?

"I also like how you can send a message to an abstract object. And that can be a
cout, a cerr, an error console in a GUI, or something else. Same thing the other
way around."

I even missed an important one. File I/O.

So if << isn't the right streaming operator, use another one. Like <- and ->. You
don't use them anyway.

To sum up: I love D. But I also like the streaming operator.



More information about the Digitalmars-d mailing list