How to use a class as key type in AAs?
JAnderson
ask at me.com
Sun Jul 6 11:44:52 PDT 2008
Koroskin Denis wrote:
> On Sun, 06 Jul 2008 22:26:46 +0400, JAnderson <ask at me.com> wrote:
>
>> Jarrett Billingsley wrote:
>>> "Moritz Warning" <moritzwarning at web.de> wrote in message
>>> news:g4r043$28f$1 at digitalmars.com...
>>>> I've read the docs and implemented size_t getHash, int
>>>> opEquals(Object o)
>>>> and int opCmp(Object o); but it still doesn't work.
>>>>
>>>> The following code prints out: 2 2 1
>>>>
>>>> Btw.: I tested (new Foo(1)) == (new Foo(1)) and it gives true,
>>>> (new Foo(1)) == (new Foo(2)) gives false.
>>>>
>>>>
>>>> void main()
>>>> {
>>>> class Foo
>>>> {
>>>> uint i;
>>>> this(uint i ) { this.i = i; }
>>>>
>>>> size_t getHash()
>>>> {
>>>> return this.i;
>>>> }
>>>>
>>>> int opEquals(Object o)
>>>> {
>>>> auto t = cast(Foo) o;
>>>> if(t is null) return false;
>>>> return (this.i == t.i);
>>>> }
>>>>
>>>> int opCmp(Object o)
>>>> {
>>>> return opEquals(o);
>>>> }
>>>> }
>>> You don't have opCmp implemented correctly. opEquals returns true
>>> if they are equal, while opCmp returns 0.
>>> It should be
>>> int opCmp(Object o)
>>> {
>>> auto t = cast(Foo)o;
>>> if(t is null)
>>> return 1;
>>> return i < t.i ? -1 : i > t.i ? 1 : 0;
>>> }
>>
>> Or just
>>
>> int opCmp(Object o)
>> {
>> auto t = cast(Foo)o;
>> if(t is null)
>> return 1;
>>
>> return i - t.i;
>> }
>>
>> -Joel
>
> Be careful, it is fast but gives wrong result when comparing int.min and
> int.max!
> I personally think that opCmp should return -1, 0 or 1 *only*. That's
> both safer and allows more advanced tricks.
True, but at least in my line of work using values in the min/max range
is rare and you can always do something different if your using byte or
unsigned. Having to branch during this sort of operation can be very
expensive since it can live in the innermost of loops.
-Joel
More information about the Digitalmars-d-learn
mailing list