opCmp with structs

BBaz via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Nov 7 02:24:01 PST 2015

On Saturday, 7 November 2015 at 10:15:25 UTC, Alex wrote:
> So the question remains, how to sort? Do you think removing the 
> immutable property from an id is the semantically right way? Or 
> do you have a hint, maybe something like, a dup copy with 
> removing immutability and returning a new, sorted copy? If you 
> think the latter is the way to choose, how is the syntax there? 
> ;)

This fails because in sort() a struct is considered as a value, 
so the instance are not moved, it looks like this() is called 
using the instance of another slot.

So to get rid of that use some pointer to struct, here when 
sort() will have to move it'll move the reference:

import std.stdio;
import std.algorithm;

struct ku
	immutable int id;
	alias id this;
	this(int i)
		id = i;
	int opCmp(ref const ku rhs) const {return id - rhs.id; }

void main()
	ku*[] tt = [new ku(2),new  ku(1)];

More information about the Digitalmars-d-learn mailing list