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.
>
> rows is a private int[][] in a Matrix struct.
>
> I have added the following ...
>
> Matrix opAssign(int[][] arr)
> {
> this.rows = arr;
> // rows = arr // does not work either ...
> return this;
> }
>
> However this does not work (no error occurs, it just doesn't
do
> anything)
How are you testing it? The following worked for me:
1) Added that opAssign() to the struct. (Verified that it gets
called.)
2) Tested with the following code:
auto m2 = Matrix();
auto rows = [ [ 1, 2 ], [ 3, 4 ], [ 5, 6 ] ];
m2 = rows;
writeln(m2);
(I've tested with a dynamically generated 'rows' as well.)
Ali
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;
}
Matrix opAssign(Matrix mat)
{
writeln(__FUNCTION__);
this.rows = mat.rows;
return this;
}
Matrix opIndexAssign(A...)(int[][] arr, A arguments)
if(A.length <= 2){
writeln(__FUNCTION__);
Matrix subMatrix = opIndex(arguments);
assert(((arr.length == subMatrix.nrow()) & (arr[0].length ==
subMatrix.ncol())),
"Array dimension do not match matrix replacement.\n");
/*foreach(i, row; subMatrix.rows){
row[] = arr[i];
}*/
subMatrix = arr; // Does not work
return subMatrix;
}
Matrix opIndexAssign(A...)(Matrix mat, A arguments)
if(A.length <= 2){
writeln(__FUNCTION__);
Matrix subMatrix = opIndex(arguments);
assert(((mat.nrow() == subMatrix.nrow()) & (mat.ncol() ==
subMatrix.ncol())),
"Array dimension do not match matrix replacement.\n");
/*foreach(i, row; subMatrix.rows){
row[] = mat.rows[i];
}*/
subMatrix = mat; // Does not work
return subMatrix;
}
void main(){
// Here we test opAssign [][]int
auto a = Matrix();
a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]; // this works
writeln(a);
// opIndexAssign int[][]
a[0..2, 0..2] = [[88, 88], [88, 88]]; // this does not work
writeln(a);
auto b = Matrix();
// opAssign Matrix
b = a; // this works
writeln(b);
b = [[88, 88, 88, 88], [88, 88, 88, 88], [88, 88, 88, 88], [88,
88, 88, 88]];
// opIndexAssign Matrix
b[0..3, 0..3] = a; // this does not work
writeln(b);
}
If you uncomment the foreach lines, the opIndexAssign() work.