Operator overloading - operations on slices

abad via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Jan 21 03:15:22 PST 2016


I am trying to create a generic interface to arrays. Most 
operations except those on elements of slices.

Code:

class Table(T) {
         T[] data;

         this(T[] data) {
                 this.data = data;
         }

         auto ref opSlice(size_t x, size_t y) {
                 return new Table!(T)(data[x .. y]);
         }

         void opIndexAssign(T value) {
                 data[] = value;
         }

         void opIndexAssign(T value, size_t idx) {
                 data[idx] = value;
         }

         void opAssign(T value) {
                 opIndexAssign(value);
         }

         auto ref opIndexOpAssign(string op)(T value, size_t idx) {
                 return mixin("data[idx] " ~ op ~ "= value");
         }
}

int main(string[] args) {
         int[] data = new int[256];
         auto t = new Table!int(data);
         t[] = -1; // OK
         t[1 .. 3] = 5; // OK
         t[0] = 6; // OK
         t[4] += 7; // OK
         t[4..6] += 7; // FAIL, does not compile
}

Am I missing some specific overload or is this just not possible?



More information about the Digitalmars-d-learn mailing list