Static operator overloads (again)

Christopher Wright dhasenan at gmail.com
Tue Sep 2 16:46:36 PDT 2008


Giles Bathgate wrote:
> Giles Bathgate Wrote:
> 
>> But static operator overloads are possible in D.
> 
> Example:
> 
> public class Test
> {
>         public char[] Name;
> 
>         public static Test opAddAssign(Test value)
>         {
>                 writefln(value.Name);
>                 //TODO...
>         }
> }
> 
> int Main()
> {
>         Test t;
>         Test b = new Test();
>         b.Name = "foo"
> 
>         t += b; // Translates to:   Test.opAddAssign(b);
> 
> }
> 
> The problem with this though is that there is no access to the lvalue t 
> this is because t+=b; translates to Text.opAddAssign(b);  I would like to propose a feature that given the operator overload:
> 
>  public static Test opAddAssign(Test lvalue, Test rvalue)
>  {
>  }
> 
> then
> 
> t += b; 
> 
> would translate to: 
> 
> Test.opAddAssign(t,b);
> 
> I really think this would benefit the language, without breaking anything since the compiler can distinguish between single and double parameter static operator overloads.

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.

I don't think that having operator overloads be static is such a bad 
thing, though it prevents you from overloading operators with types. 
(downs has some interesting examples to this effect...)



More information about the Digitalmars-d mailing list