Overloading operators by operator symbol

Mike Parker aldacron71 at yahoo.com
Sat Oct 28 10:26:33 PDT 2006


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'.



More information about the Digitalmars-d mailing list