Overloading operators by operator symbol

rm roel.mathys at gmail.com
Sat Oct 28 11:04:18 PDT 2006


Mike Parker wrote:
> Bill Baxter wrote:
>> I'm not a big fan of magic operator method names.  Python has its
>> __add__ etc methods, Lua has very similar, D has opAdd etc.
>> Personally I prefer C++'s way of just using the syntax itself.  I find
>> it a lot easier to remember and it looks less "magical".

Personally, I think binary operators should be static functions or
non-member functions. I understand magic to be something that is
momentarily beyond my horizon of understanding, so whatever syntax is
used ...
I think it's necessary to have operator overloading to not have to
"learn" two ways of doing operations, one for built-in types and one for
 user-defined types.

>> I started wondering if it might be able to accomplish something like
>> that using mixins.  Here's an example of what I've gotten to work so far:
> 
> The idea behind opAdd and friends is that they establish an explicit
> contract. In C++, what exactly is operator+ supposed to used for? It
> doesn't always mean 'addition'. Even in the standard library,
> std::string uses '+' to mean 'concatenation'. In some C++ vector math
> libraries, '*' is used to calculate the dot product of two vectors,
> since there's no such thing as the multiplication of two vectors (that
> is, it's not uniquely defined), while at the same time being used to
> multiply a vector by a scalar.

well with opMul you can exactly do the same, that's just syntax.
So, drawing a conclusion because in C++ you have to overload operator+
and in D you have to overload opMul ... ?

> opAdd is an explicit interface saying that "this operator does
> addition." Programmers can still abuse it, just as they can abuse the
> contract established by any interface. But when a library implementor
> uses opAdd to do concatenation or something other than addition, you can
> now point at them and say they are breaking the contract. operator+
> doesn't allow you to do that since '+' by itself does not necessarily
> equivocate to 'addition'.

where are these definitions given? Or should I "interpret" opAdd as
"operator for addition", and then again, if wonder what Webster has to
say about addition, e.g. you have to add 100 grams of sugar, then you
have to mix-in :-) 500 ml of milk ...

The more important question is, is all that is needed provided in D?
Maybe the first question should be, what is needed?

roel



More information about the Digitalmars-d mailing list