operator overloading outside the type

Walter Bright newshound2 at digitalmars.com
Sun Mar 30 03:11:48 UTC 2025


On 3/29/2025 12:24 PM, sfp wrote:
> There's nothing preventing people from writing incomprehensible "operator 
> madness"-style code in D. Whether or not `+` behaves like addition is up to the 
> programmer, and where the function `opBinary!"+"` is defined is immaterial.

If an operator overload can only be defined in the definition of the type, then 
people know where to look for it.


> Open debugger, step into `a+b`. Problem solved.

 From just reading code, an overloaded operator will not be apparent.

I recall when David Abrahams wrote a C++ regex package that used operator 
overloading for regex operations. Seeing it in action, it was surprisingly 
difficult to figure from reading the code which was C++ code and which was regex 
code.

It took maybe 10 years for the C++ community to reach the conclusion that 
iostreams was operator overloading abuse and a bad idea.


> For the highly nontrivial code that I write, being able to define operators as 
> free functions would make my code simpler. Being forced to define them as member 
> functions results in ugly, tortured code.

I have not seen your code and so cannot form an opinion about it. No doubt it is 
possible to write good code with freestanding operator overloads. But the 
history of it is not encouraging.

I've often had the fortune (or misfortune!) of having to work on code I haven't 
touched for 5 years or more, and it being quite baffling. Once I figure it out 
again, I wind up redoing it for better clarity. Sometimes that meant making the 
code less clever.




More information about the Digitalmars-d mailing list