【发布时间】:2016-05-28 17:51:08
【问题描述】:
我在 D 中有以下代码:
import std.stdio;
import std.container.array;
class RefType { }
class MyContainer {
private Array!RefType test;
RefType result() const { // I want const on this, not on return type
return test[0]; // use opIndex() from Array(T)
// Error: cannot implicitly convert expression (this.test.opIndex(0u))
// of type const(RefType) to main.RefType
}
}
int main(string[] argv) {
auto c = new MyContainer; auto r = c.result(); return 0;
}
如您所见,我想从自定义容器类返回引用类型。但是 Array 的 opIndex() 并没有给予这样做的权限,为什么?
我认为 opIndex() 应该返回 RefType 而不是 const(RefType) 值,因为数组是 Array!RefType。
这是一个错误吗?还是设计意图?如果这是有意的设计,我怎样才能得到我想要的?
【问题讨论】:
-
尝试将您的
const替换为inout。所以inout(RefType) result() inout { return test[0]; }看看是否适合你 -
是的,这行得通!但是 inout 关键字的含义是什么?
-
我已经测试过并且没有破坏 constness :) 请将其设置为答案。这只是我发现的。
-
inout可用作 mutable、immutable 和 const 的可变占位符,允许接受其中任何一个。但是inout作为参数的行为类似于scope const如果我是正确的。
标签: constants d type-safety