www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Operator overloading - operations on slices

reply abad <abad.flt gmail.com> writes:
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?
Jan 21 2016
parent abad <abad.flt gmail.com> writes:
On Thursday, 21 January 2016 at 11:15:22 UTC, abad wrote:
 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?
I got it to work by adding this: auto ref opSliceOpAssign(string op, this X, V, B, E)(auto ref V v, auto ref B b, auto ref E e) { return mixin("data[b..e] "~op~"= v"); } What could perhaps be improved are compiler error messages. DMD output: Error: t.opSlice(4LU, 6LU) is not an lvalue This does not really tell clearly what is going on.
Jan 21 2016