Overloading operators by operator symbol

Walter Bright newshound at digitalmars.com
Mon Oct 30 00:39:32 PST 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".

The reasons for "opAdd" instead of "operator+" are:

1) opAdd is eminently more greppable. Try grepping for operator+:

	operator /* comment */ + (T t)

	operator +\
	+()

	operator+(T t)

Oops, I found operator/ instead! I thought operator++ was operator+! Is 
that a unary + or a binary +? You practically need a full C++ front end 
to do the job correctly. D can do tolerably well with simple grep.

2) opAdd looks like "opAdd" in the object symbol table rather than "?H" 
(I am not making up ?H, it really is that) giving one a clue without 
needing a decoder ring.

3) it encourages the use of operating overloading for arithmetic 
purposes, rather than "parse this predicate once", which happens with 
C++ operator overloading.

4) operators that are mathematically related can be derived from each 
other: in C++ the == and != are separately overloadable. Anyone who 
wants to do mathematical overloading has to do both and take care that 
one actually is the not of the other. With opEquals, one function can 
serve both. This makes more of a difference with <, <=, >, >= where 4 
overloads are replaced by opCmp.

5) Note C++'s inability to distinguish operator[] as an lvalue and as an 
rvalue. D has opIndexAssign and opIndex.

6) Note the kludge-o-matic C++ overloading of operator++ and its 
different meanings. I can never remember which is which without looking 
it up. D has opAddAssign and opPostInc.



More information about the Digitalmars-d mailing list