First of all, sorry for being late, I was at vacation...
If you return a reference, then you have to have an object to refer
to. Where do you propose to store that object?
Of course, in your Matrix class your object should be stored.
I think its well known
that this scheme is impossible to implement correctly and safely. See
for instance Effective C++ by Scott Meyer who gives all the various
flawed possibilities a good going over.
I'm sorry, but I haven't read this book.
Unless of course you have some code that shows differently ...
So what's wrong with e.g. this:
#include <iostream>
#include <ostream>
#include <vector>
template <int rows,int cols> class Matrix
{
private:
double mat[rows][cols];
public:
class Proxy {
private:
Matrix* m;
int row;
friend class Matrix;
void SetRow(int r)
{ row = r;}
void SetMat(Matrix* matrix)
{ m = matrix;}
public:
Proxy() {}
const double& operator [](int i) const;
double& operator [](int i);
};
friend class Proxy;
private:
std::vector<Proxy> prox;
public:
Matrix() : prox(rows)
{
for (unsigned int r=0;r<rows;r++)
{
prox[r].SetRow(r);
prox[r].SetMat(this);
}
}
const Proxy& operator[] (int i) const
{
return prox
;
}
Proxy& operator[] (int i)
{
return prox;
}
};
template <int rows, int cols>
const double& Matrix<rows,cols>:roxy:perator[](int i) const
{
return m->mat[row];
}
template <int rows, int cols>
double& Matrix<rows,cols>:roxy:perator[](int i)
{
return m->mat[row];
}
int main()
{
Matrix<4,4> m;
for (unsigned int r=0;r<4;r++)
for (unsigned int c=0;c<4;c++)
{
std::cout << r << " " << c <<std::endl;
m[r][c] = r+c;
}
for (unsigned int r=0;r<4;r++)
{
for (unsigned int c=0;c<4;c++)
std::cout << m[r][c] << " ";
std::cout << std::endl;
}
return 0;
}