Overloading relational operators separately; thoughts?

Jonathan M Davis via Digitalmars-d digitalmars-d at puremagic.com
Tue Sep 27 23:05:54 PDT 2016


On Wednesday, September 28, 2016 03:28:50 Minty Fresh via Digitalmars-d wrote:
> Lastly, if operators are intended to behave so strictly, why does
> this not extend then to binary arithmetic operators (+, -, *, /,
> %, etc.)
> They don't follow the same rules as the binary relational
> operators, after all.

It's not possible in the general case to define the arithmetic operators as
functions of each other. They actually need to be defined separately in
order to work. The comparison operators don't have that problem. And in the
cases where the arithmetic operations are essentially being passed on to a
member variable such that it's just the operator itself that's changing, and
the code is otherwise the same, the fact that opBinary takes a string for
the operator makes it trivial to use string mixins so that you only need one
function body for all of the operators, whereas in the cases where you can't
do that (e.g. the operation involves multiple member variables), you can
declare separate functions.

The increment and decrement operators are in a similar boat to the
comparison operators in that post and pre can be derived from a single
function. So, it's not just the comparison operators that got combined. In
the cases where it made sense to combine operators, they were combined, and
in the cases where it didn't make sense, they weren't. It would be nice if
more could be combined, but most of them actually need to be separate to
work. Fortunately though, some of them can be combined, and those were
combined, which makes operator overloading in D easier and less error-prone.

- Jonathan M Davis



More information about the Digitalmars-d mailing list