D
Denis Remezov
Mario said:.
Hi,
It's possible to overload the [] operator, but I wonder if it's possible to
somehow overload [][] and so forth.
My goal would be to switch from static array declaration into something
totaly dynamic with minimal change in the code.
The following code
int foo[NB_ROW][NB_COL];
foo[12][3] = 0;
would become:
Array2DimInt foo(NB_ROW, NB_COL);
foo[12][3] = 0;
A vector<vector<int> > that Dan suggested would work, but it is a bit too
generic for matrices (each row stores its own dimension, which you need
to care about). In some cases its suboptimal memory usage can be a factor
as well. Here are two more choices:
a) (Sean beat me to it, but I'm going to post this anyway since I've
typed it already).
Make the first [] return a proxy object. Here is an example idea
(it didn't feel right not making it a template):
template <typename T>
class Array2Dim {
vector<T> data_;
int width_;
public:
class RowProxy {
friend class Array2Dim;
vector<T>& data_;
int ofs_;
RowProxy(vector<T>& data, int ofs) : data_(data), ofs_(ofs) {}
public:
T& operator [](int col) {
return data_[ofs_+col];
}
};
RowProxy operator [](int row) {
return RowProxy(data_, row*width_);
}
//...
};
b) Consider using the (i, j) notation instead of [j]. I prefer the
[j] syntax, but (i, j) is superior in its implementation.
(Use operator() (int row, int col)).
Though as you mentioned you wanted to minimise the change to the existing
code, this may not work well for you.
Denis