Bug 2305 – ".sort" on array of struct can't use templated "opCmp"

Status
RESOLVED
Resolution
WONTFIX
Severity
enhancement
Priority
P2
Component
dmd
Product
D
Version
D1 (retired)
Platform
x86
OS
Windows
Creation time
2008-08-22T15:13:32Z
Last change time
2019-08-20T11:42:04Z
Assigned to
No Owner
Creator
Florent GABRIEL

Comments

Comment #0 by tsalm — 2008-08-22T15:13:32Z
Actually, to sort an array of "struct", ".sort" don't use a templated opCmp method. Here is an example that illustrate the problem (same as in the url) : import tango.io.Stdout; struct A{ int i; static A opCall(int j){ A a; a.i=j; return a; } int opCmp(T)(T b) { static if (is(T:A)||is(T:A*)) return (i-b.i); else return false;} } struct B{ // opposite ordering int i; static B opCall(int j){ B res; res.i=j; return res; } int opCmp(T)(T b) { static if (is(T:B)||is(T:B*)) return -(i-b.i); else return false; } } void main() { int a=1,b=2; A a2=A(a),b2=A(b); Stdout("A")(a2.opCmp(b2))(" ")(a2<b2).newline; auto aa2=[a2,b2]; B a3=B(a),b3=B(b); Stdout("B")(a3.opCmp(b3))(" ")(a3<b3).newline; auto aa3=[a3,b3]; aa2.sort; aa3.sort; foreach(v;aa2) Stdout( v.i )(" "); Stdout.newline; foreach(v;aa3) Stdout( v.i )(" "); Stdout.newline; }
Comment #1 by razvan.nitu1305 — 2019-08-20T11:42:04Z
D2 array do not have a sort property, but std.algorithm.sort can be used and it works. Closing...