I\'m trying to write a dynamic array template in c++
I\'m currently overloading the [] operators and I\'d like to implement a different behavior based on which side
Scott Meyers talked about this in one of the Effective C++ books. Basically the trick was to return a temporary const- or non-const proxy object from the index operators (operator[]() and operator[]() const), then overload the assignment and implicit conversion operators for that proxy class. Something like this:
template
class Array
{
public:
struct proxy {
T& element;
proxy(T& el) : element(el) {}
operator const T& () const {
return element; // For use on RHS of assignment
}
proxy& operator=(const T& rhs) {
// For use on LHS of assignment
// Add your logic here
}
};
const proxy operator[](int i) const {
return proxy(a[i]);
}
proxy operator[](int i) {
return proxy(a[i]);
}
private:
T* a;
};
I may have some of the details wrong but the idea is to defer the decision of what side of the assignment the element is on until an actual attempt is made to assign to it. That is, you don't know what will be done at the time of the operator[] call, but you certainly do when you attempt to assign to the subsequent element reference.