Const / ref task in D

I am trying to implement my own range in D and I am having problems with its .front() method.

Edit:

I need the return value to be on ref .

  • If I do this const , then the returned object will be a copy that is not what I want.

  • If I do not make it const , then I cannot use .front in const copies of my range at all.

How to solve this?

 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 } 
+7
source share
2 answers

Try the following:

 struct MyRange(T) { T[] buf; @property ref T front() { return this.buf[0]; } @property ref const(T) front() const { return this.buf[0]; } } 

The problem in your example is that you created a front const, but not a return value, and the compiler will not allow you to avoid mutable references to const data like this.

Now, I would like to point out that in general, you should not expect constant ranges to work very well. By their very nature, they must be mutable to popFront over them (since you cannot call popFront in the constant range), so you cannot do much outside the front and empty with the constant range. The situation would not be just as bad if you could implicitly convert a range of constants to a range of tail-constants, but this only works with arrays and no one could find a good way to do this with common ranges. So, unfortunately, constant ranges are currently useless.

+7
source

what if you create a separate setter for the front:

 @property T front() const { return this.buf[0]; }//const @property void front(T t) { this.buf[0]=t; }//allows assign when needed 

- that's what you need?

0
source

All Articles