来自D的文档:
或者,您可以使用auto ref参数声明单个模板化opEquals函数:
Run Code Online (Sandbox Code Playgroud)bool opEquals()(auto ref S s) { ... }<...>
如果struct声明了一个opCmp成员函数,它应该遵循以下形式:
Run Code Online (Sandbox Code Playgroud)int opCmp(ref const S s) const { ... }
为什么以下代码无法编译呢?
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);
}
Run Code Online (Sandbox Code Playgroud)
这是DMD的输出:
/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))
Run Code Online (Sandbox Code Playgroud)
const写完之后没有考虑到.这应该工作:
bool opEquals()(auto const ref Fgs another) const
Run Code Online (Sandbox Code Playgroud)
但是这是一个有点处于不稳定状态的语言区域,auto ref将来可能会在非模板上使用.