Static operator overloads (again)

Jarrett Billingsley jarrett.billingsley at gmail.com
Mon Sep 1 07:52:31 PDT 2008


On Mon, Sep 1, 2008 at 9:11 AM, Giles Bathgate <gilesbathgate at gmail.com>wrote:

> I am trying to translate the following C# code into D
>
>     public class Test
>        {
>            public string Name;
>
>            public static Test operator +(Test lvalue, Test rvalue)
>            {
>                if (lvalue == null) { lvalue = new Test(); lvalue.Name =
> "foo"; }
>                if (rvalue == null) { rvalue = new Test(); rvalue.Name =
> "bar"; }
>
>                Console.Write(lvalue.Name);
>                Console.Write(rvalue.Name);
>
>                return rvalue;
>            }
>
>        }
>
> void main()
> {
>    Test T = null;
>    Test B = null;
>    T += B;
> }
>
> Whilst leaving the syntax of main() untouched.
>
>
Long story short: I really don't think you can.  Operator overloading in D
can only be performed as nonstatic methods of user-defined types.  Since a
virtual method call requires that the object you're calling it on be
non-null (so that you can get the vtable), you can't use overloaded
operators on null references.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.puremagic.com/pipermail/digitalmars-d/attachments/20080901/d3f43a38/attachment.html>


More information about the Digitalmars-d mailing list