matrix: fix slice to slice assignment to do deep copy

To fix usage of a.xy() = b.xy() which should copy
the first two elements over into a and not act on a copy of a.
This commit is contained in:
Matthias Grob 2023-12-20 11:58:13 +01:00
parent 2afbd09c63
commit bcb2b1ad40
2 changed files with 17 additions and 0 deletions

View File

@ -35,6 +35,8 @@ public:
assert(y0 + Q <= N);
}
Slice(const Slice<Type, P, Q, M, N> &other) = default;
const Type &operator()(size_t i, size_t j) const
{
assert(i < P);
@ -52,6 +54,12 @@ public:
return (*_data)(_x0 + i, _y0 + j);
}
// Separate function needed otherwise the default copy constructor matches before the deep copy implementation
Slice<Type, P, Q, M, N> &operator=(const Slice<Type, P, Q, M, N> &other)
{
return this->operator=<M, N>(other);
}
template<size_t MM, size_t NN>
Slice<Type, P, Q, M, N> &operator=(const Slice<Type, P, Q, MM, NN> &other)
{

View File

@ -262,3 +262,12 @@ TEST(MatrixSliceTest, Slice)
float O_check_data_12 [4] = {2.5, 3, 4, 5};
EXPECT_EQ(res_12, (SquareMatrix<float, 2>(O_check_data_12)));
}
TEST(MatrixSliceTest, XYAssignmentTest)
{
Vector3f a(1, 2, 3);
Vector3f b(4, 5, 6);
// Assign first two elements from b to first two slot of a
a.xy() = b.xy();
EXPECT_EQ(a, Vector3f(4, 5, 3));
}