Using Classes as the KeyType (from the Docs)

Andrej Mitrovic andrej.mitrovich at gmail.com
Sun Jun 20 13:50:04 PDT 2010


Hi,

There's an example in the docs about classes with a keytype which I don't fully understand. Here's the code (taken from http://www.digitalmars.com/d/2.0/arrays.html under "Using Classes as the KeyType"):

------------------------------------------------------
class Foo
{
    int a, b;

    hash_t toHash() { return a + b; }

    bool opEquals(Object o)
    {	Foo f = cast(Foo) o;
	return f && a == foo.a && b == foo.b;
    }

    int opCmp(Object o)
    {	Foo f = cast(Foo) o;
	if (!f)
	    return -1;
	if (a == foo.a)
	    return b - foo.b;
	return a - foo.a;
    }
}
------------------------------------------------------


Shouldn't this be written like this instead?:
------------------------------------------------------
class Foo
{
    int a, b;

    hash_t toHash() { return a + b; }

    bool opEquals(Object o)
    {	Foo f = cast(Foo) o;
	return f && a == f.a && b == f.b;
    }

    int opCmp(Object o)
    {	Foo f = cast(Foo) o;
	if (!f)
	    return -1;
	if (a == f.a)
	    return b - f.b;
	return a - f.a;
    }
}
------------------------------------------------------

Notice I've replaced "foo" with "f"

Foo is the class, but there's no mention of "foo". I'm guessing it was a typo, unless I'm missunderstanding something.



More information about the Digitalmars-d mailing list