opEquals footprint
Erik Rasmussen
i_am_erik at yahoo.com
Wed Mar 22 07:52:13 PST 2006
xs0 wrote:
> Erik Rasmussen wrote:
>
>> xs0 wrote:
>>
>>> int opEquals(Object)
>>>
>>> so it overrides the default implementation found in, you guessed it,
>>> Object :) Same goes for opCmp, I think..
>>>
>>>
>>> xs0
>>
>>
>> So what's the best way to actually check the type in the
>> opEquals/opCmp method? Something like...
>>
>> class A
>> {
>> int opEquals(Object o)
>> {
>> // check for null
>> if(o is null)
>> return false;
>> // check type
>> if(typeid(typeof(o)) != typeid(A))
>> return false;
>> // cast
>> A that = cast(A) o;
>> // actually check fields
>> return this.a == that.a && this.b == that.b && ...;
>> }
>> }
>>
>> Or is there a better way? asserts?
>>
>> How do you hard-core D programmers usually do it?
>>
>> Cheers,
>> Erik
>
>
> Something like this should be ok:
>
> // optional
> if (this is o)
> return true;
>
> if (A that = cast(A)o) { // checks for null, too
> return this.a==that.a && ...
> } else {
> return false;
> }
>
> OTOH, if you want to return false for subclasses, your version seems
> fine to me.
>
>
> xs0
No, I definitely don't want it to return false for subclasses!
That "failed cast returns null" trick is handy. That's waaay better
than all that typeid(typeof()) crap. Thanks guys.
Erik
More information about the Digitalmars-d-learn
mailing list