Re: operator[] with multiple arguments
In article <1153826038.312146.258780@h48g2000cwc.googlegroups.com>,
Anders Dalvander <google@dalvander.com> wrote:
Are there any suggestion for C++0X that operator[] overloads should be
allowed to support multiple arguments?
template <typename T, size_t rows, size_t columns>
class Matrix
{
public:
T operator[](size_t row, size_t column) const
{
return data[columns * row + column];
}
private:
T data[rows * columns];
// or T data[rows, columns];
};
operator [] takes one argument. Any user defined operator [] must
take one argument. That said I'd redesign this using a proxy, to
something like below allowing the 'normal' notation A[i][j] to work.
not tested but it is the general idea. Do as much as you can with the
left subscript store the results in an nested class and then compute
the result using the results saved and the right subscript.
template <....>
class Matrix
{
T data[...];
class proxy
{
T *data;
int i;
public:
proxy(T *a,int b):data(a),i(b);
T & operator [] (int j) const
{ return data[i + j]; }
};
public:
proxy operator [] (int i) {return proxy(data,i*columns);}
};
Matrix<...> A;
A[i][j] is (A[i])[j] A[i] returns a Matrix::proxy and then calls
Matrix::proxy::operator [](j) which returns a T & to the A[i][j] in the
'usual sense'.
If I see A[a,b] a red light goes up this is accessing A[b] after a is
computed.
---
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.comeaucomputing.com/csc/faq.html ]