This is incorrect code according to the spec but it doesn't really make sense to me why it doesn't work.
So the spec says:
"""
For the .sort property to work on arrays of structs or unions, the struct or union definition must define the function: int opCmp(S) or int opCmp(S*). The type S is the type of the struct or union. This function will determine the sort ordering.
"""
But I just happened to use opCmp(ref S) and it seemed to work (everything compiled fine and ran without crashing, anyway).
But it doesn't actually work. Sorting sorts improperly.
I think making a ref opCmp in a struct should either be made to work (i see no reason why it should not work), or it should be made a compiler error to try to create one.
Attached is a simple test.
Comment #1 by wbaxter — 2007-09-19T02:45:32Z
Created attachment 185
Simple test
Comment #2 by bearophile_hugs — 2010-03-17T20:10:47Z
Reduced test case, on dmd v2.041:
struct S {
int i;
int opCmp(S other) {
return this.i - other.i;
}
}
void main() {
S[S] aa;
foreach (int i; [1, -1, 7])
aa[S(i)] = S(-i);
// wrong order:
assert(aa.keys.sort == [S(1), S(7), S(-1)]);
}
If this is a real bug (and it seems so) then I think it's serious bug, it's worse than a compiler crash, because the program runs unreliably.
Comment #3 by yebblies — 2014-08-31T13:52:21Z
I get
object.Error@(0): TypeInfo.compare is not implemented
On recent dmd (2.067 HEAD), and given that builtin .sort is going away this is WONTFIX for D2.