How to use a class as key type in AAs?

Moritz Warning moritzwarning at web.de
Sun Jul 6 10:41:24 PDT 2008


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);
		}
	}
 
	uint[Foo] all;
 
	all[new Foo(1)] = 0;
	all[new Foo(2)] = 0;
	all[new Foo(2)] = 0;
 
	foreach(k, v; all)
	{
		Stdout(k.i).newline;
	}
}


More information about the Digitalmars-d-learn mailing list