In article <46d17343$0$27399$ba4acef3@news.orange.fr>,
jacob@jacob.remcomp.fr says...
Quote:
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;
Make it const and have it return a reference to const. This prevents you
from writing to the data (at all) via the operator:
class bad_subscript {};
template <class T>
class const_array {
T *data_;
size_t size_;
public:
const_array(T *init, size_t size) :
size_(size), data_(new T[size])
{
std::copy(init, init+size, data_);
}
T const &operator[](size_t subscript) const {
if (subscript size_)
throw bad_subscript();
return data_[subscript];
}
T *raw_data() { return data_; }
size_t size() { return size_; }
};
raw_data() is a quick hack to allow writing to the data -- you haven't
said when or how you want to allow writing to the data, so I've provided
one way to do it. If you _only_ want to allow the data to be
initialized, you can eliminate it (and probably add more ctors to allow
more than one form of intialization).
--
Later,
Jerry.
The universe is a figment of its own imagination.