我正在尝试在 D 中实现我自己的范围,但我遇到了问题 .front()
方法。
编辑:
我需要返回值是 来自 ref
.
const
,那么返回的对象将是一个副本,这不是我想要的。const
,那我就不能用 .front
在 const
我的范围的副本。我该如何解决这个问题?
struct MyRange(T)
{
T[] buf;
@property ref T front() { return this.buf[0]; } // No error, but not const
@property ref T front() const { return this.buf[0]; } // Errors
@property T front() const { return this.buf[0]; } // No error, but a copy
// Can't have all three
}
最佳答案
尝试这个:
struct MyRange(T)
{
T[] buf;
@property ref T front() { return this.buf[0]; }
@property ref const(T) front() const { return this.buf[0]; }
}
您示例中的问题是您制作了
front
const 而不是返回的值,编译器不会让你像这样转义对 const 数据的可变引用。现在,我要指出的是,一般而言,您不应该期望 const 范围能够很好地工作。就其本质而言,它们需要可变才能迭代它们(因为您不能在常量范围内调用
popFront
),因此除了使用 front
之外,您将无法做太多事情。和 empty
具有常量范围。如果您可以将 const 范围隐式转换为 tail-const 范围,情况就不会那么糟糕,但这仅适用于数组,而且还没有人想出一种使用通用范围的好方法。所以不幸的是,const 范围在这一点上基本上是无用的。
关于constants - D 中的 const/ref 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6976019/