On Friday, 25 March 2016 at 08:53:20 UTC, Ali Çehreli wrote:
On 03/25/2016 12:00 AM, data pulverizer wrote:
> On Thursday, 24 March 2016 at 18:46:14 UTC, Ali Çehreli wrote:
>> On 03/24/2016 10:24 AM, data pulverizer wrote:
>> > I have been playing with the matrix example given at the
end
>> of chapter
>> > 78 of Ali Çehreli's
>>
>> For reference, it's "Multi-dimensional operator overloading
example"
>> here:
>>
>>   http://ddili.org/ders/d.en/templates_more.html
>>
>> >having problems with overloading the opAssign operator.

> Thank you. Let me try to ask the question again. The problem
I am
> experiencing is to do with opIndexAssign().
>
> I added the following public operators:
>
>      Matrix opAssign(int[][] arr)
>      {
>          writeln(__FUNCTION__);
>          this.rows = arr;
>          return this;
>      }

The problem is due to the aliasing of 'rows' members of Matrix objects. subMatrix is supposed to be a reference into some elements of an existing Matrix. As soon as we do the above assignment, this Matrix (which may be a subMatrix in a specific context) breaks lose from its actual Matrix elements.

We need to implement the function above "in place":

    Matrix opAssign(int[][] arr)
    {
        writeln(__FUNCTION__);

        if (rows.length < arr.length) {
            rows.length = arr.length;
        }

        foreach (i, row; arr) {
            const newLength = row.length;

            if (rows[i].length < newLength) {
                rows[i].length = newLength;
            }
            rows[i][0..newLength] = row[];
        }

        return this;
    }

(There must be an existing function that does that.)

>      Matrix opAssign(Matrix mat)
>      {
>          writeln(__FUNCTION__);
>          this.rows = mat.rows;

Same thing applies above: We need to assign to this.rows in place (which is easier by taking advantage of the previous function):

        this = mat.rows;

>          return this;
>      }

No changes needed for the other two functions but I would 'return this' instead of 'return subMatrix' for them as well.

Ali

That's great! Thank you very much for the fix and extra suggestions, and for your patience putting up with my poorly formulated question! Looks like I need to go and read all the structs and operators chapters thoroughly!

Reply via email to