jacob navia wrote:
> Hi
>
> Suppose that I want to create an array of read only items
>
> I overload the [ ] operator. How can I detect if I am being called
> within a read context
> foo = Array[23];
>
> or within a write context
> Array[23] = foo;
>
You have to use another level of indirection, something like this:
#include <iostream>
template <typename Taget, typename ArrayType>
class Proxy {
Taget& target;
unsigned index;
public:
Proxy( Taget& target, unsigned index )
: target(target), index(index) {}
Proxy& operator=( ArrayType t ) {
std::cout << "rhs " << index << std::endl;
return *this;
}
operator ArrayType() const {
std::cout << "lhs " << index << std::endl;
return 42;
}
};
struct Test {
typedef Proxy<Test, int> ProxyType;
const ProxyType operator[]( unsigned index ) const {
return ProxyType(const_cast<Test&>(*this), index );
}
ProxyType operator[]( unsigned index ) {
return ProxyType(*this, index );
}
};
int main() {
Test test;
int n = test[0];
test[3] = 42;
}
--
Ian Collins.