I am trying to write a templated Matrix class that can be extended and used for other things like vectors. However, I cannot figure out why operator[]
in the Row
class, does not return the reference to the actual data_
vector in the Matrix, but a reference to a different data_
.
The code below is the code for the Matrix. I'm using a Row
class, which is hidden in a namespace so that I can use the double square brackets to access an element. In that class there is a shared pointer to the parent matrix, so that I can access the data_
vector in it from the Row
class, which doesn't seem to work though.
#ifndef YAGE_MATH_MATRIX_HPP
#define YAGE_MATH_MATRIX_HPP
#include <iostream>
#include <memory>
#include <vector>
namespace yage
{
template<int Rows, int Cols, class Type> class Matrix;
namespace detail
{
template<int Rows, int Cols, class Type> class Row
{
private:
std::shared_ptr<Matrix<Rows, Cols, Type>> parent_;
int index_;
public:
Row<Rows, Cols, Type>(std::shared_ptr<Matrix<Rows, Cols, Type>> parent, int index) :
parent_(parent), index_(index)
{}
Type &operator[](int col)
{
std::cout<<"Other Data: "<<&parent_->data_[index_*Cols+col]<<'\n';
return parent_->data_[index_*Cols+col];
}
};
} // detail
template<int Rows=4, int Cols=4, class Type=double> class Matrix
{
friend class detail::Row<Rows, Cols, Type>;
private:
std::vector<Type> data_;
public:
Matrix<Rows, Cols, Type>() : data_(Rows*Cols) {}
Matrix<Rows, Cols, Type>(int rows, int cols) : data_(rows*cols) {}
detail::Row<Rows, Cols, Type> operator[](int row)
{
std::cout<<"Main Data: "<<&data_[10]<<'\n';
return detail::Row<Rows, Cols, Type>(std::make_shared<Matrix<Rows, Cols, Type>>(*this), row);
}
};
} // yage
#endif
I tested these classes with the following program
#include "Math/matrix.hpp"
#include <iostream>
int main()
{
yage::Matrix<4, 4> matrix;
matrix[2][2];
return 1;
}
and the output was
Main Data: 0x1f72960
Other Data: 0x1f72e30
which point to two different locations.
I know that there are different ways of solving this, for example using the operator(x, y)
overload, but I am curious about what mistake I have made.
Thank you for your help.