我正在尝试在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
}
Run Code Online (Sandbox Code Playgroud)
试试这个:
struct MyRange(T)
{
T[] buf;
@property ref T front() { return this.buf[0]; }
@property ref const(T) front() const { return this.buf[0]; }
}
Run Code Online (Sandbox Code Playgroud)
您的示例中的问题是您创建了frontconst而不是返回的值,并且编译器不会让您转义对const数据的可变引用.
现在,我想指出,一般来说,你不应该期望const范围能够很好地工作.就其本质而言,它们需要是可变的来迭代它们(因为你不能调用popFrontconst范围),所以除了使用front和empty使用const范围之外你不会做太多事情.如果你可以隐式地将const范围转换为tail-const范围,那么情况也不会那么糟糕,但是这只适用于数组,并且没有人想出一个使用常规范围的好方法.不幸的是,const范围在这一点上基本上是无用的.