array length vs $

Robert Fraser fraserofthenight at gmail.com
Sat Mar 15 11:58:42 PDT 2008


Wow, my head asplode! That's awesome! It'd stil be nicer to have it as part of the language rather than an undocumented trick.

Bill Baxter Wrote:

> Janice Caron wrote:
> 
> > I want to be able to create containers that behave just like the built
> > in ones. 
> 
> Happy Easter!
> 
> struct EndRelativeIndex {
>      /** $ - 5  */
>      EndRelativeIndex opSub(int off_) {
>          EndRelativeIndex R = *this;
>          R.offset -= off_;
>          return R;
>      }
>      /** $ + 5 */
>      EndRelativeIndex opAdd(int off_) {
>          EndRelativeIndex R = *this;
>          R.offset += off_;
>          return R;
>      }
>      /** 5 + $ */
>      EndRelativeIndex opAdd_r(int off_) {
>          EndRelativeIndex R = *this;
>          R.offset += off_;
>          return R;
>      }
> private:
>      int offset = 0;
> }
> EndRelativeIndex _end;
> 
> // Easter egg here:
> alias _end __dollar;
> 
> struct Array(T)
> {
>      T opIndex(size_t i) { return data[i]; }
>      T opIndex(EndRelativeIndex i) { return data[data.length+i.offset]; }
> 
>      T[] data;
> }
> 
> void main() {
>      Array!(int) x;
>      x.data = [1,2,3,4,5];
> 
>      assert(x[0] == 1);
>      assert(x[$-1] == 5);
>      assert(x[$-2] == 4);
> }
> 
> --bb




More information about the Digitalmars-d mailing list