putting more smarts into a == b

Christopher Wright dhasenan at gmail.com
Sun Sep 27 05:38:25 PDT 2009


Jarrett Billingsley wrote:
> On Sat, Sep 26, 2009 at 9:32 PM, Andrei Alexandrescu
> <SeeWebsiteForEmail at erdani.org> wrote:
>> Consider two objects a and b with a of class type. Currently, the expression
>> a == b is blindly rewritten as a.opEquals(b). I argue it should be rewritten
>> into a call to an (imaginary/inlined) function equalObjects(a, b), with the
>> following definition:
>>
>> bool equalObjects(T, U)(T a, U b) if (is(T == class))
>> {
>>    static if (is(U == class))
>>    {
>>        if (b is null) return a is null;
>>        if (a is null) return b is null;
>>    }
>>    else
>>    {
>>        enforce(a !is null);
>>    }
>>    return a.opEquals(b);
>> }
>>
>> This hoists the identity test outside the opEquals call and also deals with
>> null references. What do you think?
> 
> I'm almost sure that C# does this already, and it's a useful behavior.

C# operator overloads are of the form:
public static ReturnType operator+(Arg1 arg1, Arg2 arg2) {}

Object.operator== is defined to call arg1.Equals(arg2) if arg1 isn't 
null. But this isn't a feature of operator overloads.

> Of course, with nonnull types, the check for null wouldn't even need
> to exiiiiiiiist.... ;)

How clever and insightful of you!



More information about the Digitalmars-d mailing list