gpt4 book ai didi

d - 无法覆盖结构的 opCmp 和 opEquals

转载 作者:行者123 更新时间:2023-12-04 02:44:06 24 4
gpt4 key购买 nike

来自 D 的 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 { ... }

为什么下面的代码编译失败?

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);
}

这是 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))

最佳答案

const 在编写时没有考虑在内。这应该有效:

bool opEquals()(auto const ref Fgs another) const

但这是语言的一个有点不稳定的领域,将来可能会在非模板上使用 auto ref

关于d - 无法覆盖结构的 opCmp 和 opEquals,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14042298/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com