Static operator overloads (again)

Christopher Wright dhasenan at gmail.com
Wed Sep 3 17:14:15 PDT 2008


Giles Bathgate wrote:
> Christopher Wright Wrote:
> 
>> I don't particularly think that it would benefit the language. There's 
>> no difference between a method call and using an operator overload. If 
>> you find yourself doing a lot of null checks, you might want to check 
>> out the Null Object pattern.
> 
> The point is when I write 
> 
> t += b;
> 
> I don't expect a null reference exception. With operator overloads the only way (that made sense to me) to achieve this was to make the opCatAssign method static, but then my dilemma is that I no longer have an access to the value of t within the opCatAssign method call.

On the other hand, what about subclasses? They can't override the 
behavior of an operator overload, if operator overloading uses static 
methods. You're reduced to writing your overloads as:

class Foo
{
	static Foo opAddAssign (Foo left, Foo right)
	{
		return left.addAssign(right);
	}
}

So your proposal eliminates two valid use cases and breaks existing 
syntax and expectations. The only benefit you get is being able to use 
null in an operator overload, which is also an unexpected change from 
the existing system.

Just use the Null Object pattern. It's intended to solve exactly the 
sort of problem you have, and it works with methods as well.



More information about the Digitalmars-d mailing list