array length vs $

Bill Baxter dnewsgroup at billbaxter.com
Sat Mar 15 10:05:41 PDT 2008


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