On Wednesday, 20 April 2016 at 10:32:42 UTC, Jeff Thompson wrote:
On Wednesday, 20 April 2016 at 09:54:13 UTC, Jeff Thompson wrote:
I can create a mutable array of immutable objects, thanks to the answers to my other question https://forum.dlang.org/post/[email protected] .

Now I want to sort the array.

I found a solution, but I'm not sure it is the best way. Instead of overriding opCmp, class C just defines a static comparison to use with sort (which automatically works with Rebindable). Is there a way to do this where I don't need to specify C.isLess every time I sort?

class C {
  this(int x) immutable { this.x = x; }
static bool isLess(const C a, const C b) @safe pure nothrow { return a.x < b.x; }
  int x;
}

void
main(string[] args)
{
  auto array = new Rebindable!(immutable(C))[2];
  array[0] = new immutable C(20);
  array[1] = new immutable C(10);
  sort!(C.isLess)(array);
}

int opCmp(immutable Object o) immutable {}

That seems to work for me. You want to make it const Object and inout if you want it to work on const and mutable C's as well. Also note that sort (std.algorithm.sorting : sort) returns a range and doesn't sort in place.

(Lastly this is probably more at home in the Learn forum.)

Reply via email to