From D's documentation:
Alternatively you can declare a single templated opEquals function with an auto ref parameter:
bool opEquals()(auto ref S s) { ... }
<...>
If structs declare an opCmp member function, it should follow the following form:
int opCmp(ref const S s) const { ... }
Why does the following code fail to compile, then?
import std.stdio;
import std.conv;
struct Fgs {
int v;
this(int iv) {
v = iv;
}
bool opEquals()(auto ref Fgs another) {
return v == another.v;
}
int opCmp(ref const Fgs another) const {
if (this == another) {
return 0;
} else if (this.v < another.v) {
return -1;
} else {
return 1;
}
}
}
unittest {
auto a = Fgs(42);
auto b = Fgs(10);
assert(a != b);
assert(a > b);
}
Here'd DMD's output:
/home/mfag/lighthouse/testss.d(15): Error: template testss.Fgs.opEquals does not match any function template declaration
/home/mfag/lighthouse/testss.d(10): Error: template testss.Fgs.opEquals() cannot deduce template function from argument types !()(const(Fgs))
const
wasn't taken into account when that was written. This should work:
bool opEquals()(auto const ref Fgs another) const
But this is an area of the language that's a bit in a state of flux, using auto ref
might be possible on non-templates in the future.