To accomplish what you want, you generally need to have operator[]
return a proxy, and overload operator=
and operator T
(where T
is the original type) for that proxy type. Then you can use operator T
to handle reads, and operator =
to handle writes.
Edit: the basic idea of a proxy is pretty simple: you return an instance of an object that acts in place of the original object. For the moment, this is going to have really trivial semantics (just read and write a char at a specified index in a vector); in your case, the logic inside of the operator=
and (especially) operator T
will apparently be more complex, but that has little or no effect on the basic structure.
#include <vector>
class X {
std::vector<char> raw_data;
class proxy {
X &parent;
int index;
public:
proxy(X &x, int i) : parent(x), index(i) {}
operator char() const { return parent.raw_data[index]; }
proxy &operator=(char d) {
parent.raw_data[index] = d;
return *this;
}
};
public:
X() : raw_data(10) {}
proxy operator[](int i) { return proxy(*this, i); }
};
#ifdef TEST
#include <iostream>
int main() {
X x;
for (int i=0; i<10; i++)
x[i] = 'A' + i;
for (int i=0; i<10; i++)
std::cout << x[i] << "\n";
return 0;
}
#endif