opCmp with structs
Ali Çehreli via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Fri Nov 6 16:19:55 PST 2015
On 11/06/2015 02:54 PM, Alex wrote:
> I'm sure I'm doing a silly mistake somewhere, but why this doesn't work?
> 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 = [ku(2), ku(1)];
> sort(tt);
> }
Continuing from your hint: So, opCmp works but it is sort() that cannot
move objects of ku around because of that immutable variable.
There may be references to ku objects or its id members and those
references may be depending on the immutability of that member. const
and immutable members effectively make objects unassignable. (const part
is the same in C++.)
Ali
More information about the Digitalmars-d-learn
mailing list