implementing default opCmp
Steven Schveighoffer
schveiguy at gmail.com
Wed Nov 18 22:29:17 UTC 2020
I have a struct like this:
struct S
{
int x;
int y;
}
and I want a default comparison. The problem is, that comparison doesn't
have a default, and requires I implement opCmp. While this is useful for
the compiler, there's no default I know of that is an easy one-liner.
The truth is, I'm not entirely caring what order these things come out
in. I just want them to be defined as having an order given that all the
members have a defined order. My expectation is that a default opCmp
would look like:
int opCmp(S other)
{
if(x == other.x)
{
if(y == other.y) return 0;
return y < other.y ? -1 : 1;
}
return x < other.x ? -1 : 1;
}
But really, as long as there is something to do this easily I don't care
what the ordering turns out to be.
I can do equality like:
return this.tupleof == other.tupleof;
I can do assignment like:
this.tupleof = other.tupleof;
How do I do something really simple for opCmp? I tried this it didn't work:
return this == other ? 0 :
this.tupleof < other.tupleof ? -1 : 1;
-Steve
More information about the Digitalmars-d-learn
mailing list