www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - sort!("a < b")( arr ); - opCmp

reply Joel Christensen <joelcnz gmail.com> writes:
How do you override "int opCmp( Object obj )"? What can I do with obj? 
The override is in a class with a double number to compare with.

I made a list of my own class objects but I haven't managed to use 
`sort!"a < b"( arr );` on it. int's and string's work on it.


Jun 17 2011
parent reply David Nadlinger <see klickverbot.at> writes:
On 6/18/11 1:40 AM, Joel Christensen wrote:
 How do you override "int opCmp( Object obj )"? What can I do with obj?

You can do pretty much whatever you want with it – obviously, you should not modify obj, because comparison is not generally expected to modify its arguments, but at the moment, that's not enforced via const or something like that. That said, your opCmp should return a negative number (-1 usually) if a is smaller than b, 0 if they are equal, and a positive number (1) if a is larger than b. An implementation of Square.opCmp might look like this (untested): --- override int opCmp(Object o) { auto rhs = cast(Square)o; if (rhs) { return (<whatever you want, using this and rhs members>); } // o wasn't actually a Square, pass it to the base class // implementation (the one in Object errors out). return super.opCmp(o); } --- David
Jun 17 2011
parent Joel Christensen <joelcnz gmail.com> writes:
Yeah, it works now. Thanks David :-)

I have actually used "<type> o = cast(<type>)<variable>;" But had 
forgotten about it. Though the super part of what you said is more subtle.
Jun 17 2011