Overloading operators by operator symbol

Chris Nicholson-Sauls ibisbasenji at gmail.com
Sat Oct 28 10:59:56 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".
>>
>> 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.
> 
> 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'.

Additionally, it allows for some minimizing.  For example, instead of an 'operator<', an 
'operator>', and an 'operator==' to make a class comparable, we merely define an 'opCmp' 
that does the work of all three.  There could yet be some more minimizing (I feel that 
opApply(dg)/opApplyReverse(dg) could, for example, become opApply(dg,reverse?) instead).

-- Chris Nicholson-Sauls



More information about the Digitalmars-d mailing list