"+=" (overloads) with custom array slices on both lhs, and rhs ??

james.p.leblanc james.p.leblanc at gmail.com
Sun Sep 5 19:43:20 UTC 2021


Dear D-ers,

I have constructed a custom array type that works, but is missing
correct functioning on some operator overloads.

The stripped down minimum example (module) was over 100 lines (due
overloading opAssign, etc.) Probably too long to be a good forum 
post.

However, a short main may explain the issue succinctly (at end).

In words: the standard D static arrays, and dynamic array can do a
"vector accumulation" using:

```d
f += g;
```

We can even have slices on both lhs and rhs:

```d
f[ 2 .. 5 ] += g[ 4 .. 7 ];
```

So, this **should** be possibly for custom array types.  I have
looked at opIndexOpAssign, and learned a great deal from Michael
Parkers book on the use of opSlice, etc. with overloads.  Also, I 
have
searched for clues in the dmd source code ... but it was not
easy to perceive how this is done.

Here is an ugly code example (without module code -- so maybe 
useless).

How does one overload custom types with "+=" and slices on both 
left and right?

Thanks in advance,
James

**compilation error message appear as comments to right of 
offending lines**

==============================================================
```d
import std.stdio;
import myarray_mod;

void main(){

    // static arrays
    int[7] x = [ 10, 11, 12, 13, 14, 15, 16 ];
    int[7] y = [ 100, 101, 102, 103, 104, 105, 106 ];

    // custom "arrays"
    auto f = myArray( x.ptr, 7 );
    auto g = myArray( y.ptr, 6 );

    f[ 1 ] += 909;           // accumulating a scalar works fine


    f[] += 909;              // "f.opIndex() is not an lvalue and 
cannot be modified
    f += g;                  // f is not a scale is is a myArray
    f[ 2 .. 5 ]+=g[ 2 .. 5]; //f.opIndex(f.opSlice(2LU, 5LU ... 
(possible missing[])

    // for standard dynamic arrays, this works fine
    int[] a = [ 1, 2, 3, 4, 5, 6 ];
    int[] b = [ 4, 5, 6, 7, 8, 9 ];
    writeln("a: ", a);
    writeln("b: ", b);
    a[ 1 .. 4 ] += b[ 2 .. 5 ];  // even with slices on both lhs & 
rhs!!
    writeln("a: ", a);

    return;
}

```



More information about the Digitalmars-d-learn mailing list