The story begins with something I thought pretty simple :
I need to design a class that will use some STL containers. I need to give users of the class access to an
Rather than providing the user with the entire container, could you just provide them non-const iterators to beginning and end? That's the STL way.
You need a custom data structure iterator, a wrapper around your private list.
template<typename T>
class inmutable_list_it {
public:
inmutable_list_it(std::list<T>* real_list) : real_list_(real_list) {}
T first() { return *(real_list_->begin()); }
// Reset Iteration
void reset() { it_ = real_list_->begin(); }
// Returns current item
T current() { return *it_; }
// Returns true if the iterator has a next element.
bool hasNext();
private:
std::list<T>* real_list_;
std::list<T>::iterator it_;
};
The painful solution:
/* YOU HAVE NOT SEEN THIS */
struct mutable_int {
mutable_int(int v = 0) : v(v) { }
operator int(void) const { return v; }
mutable_int const &operator=(int nv) const { v = nv; return *this; }
mutable int v;
};
Excuse me while I have to punish myself to atone for my sins.
The simplest option would probably be a standard STL container of pointers, since const
-ness is not propagated to the actual objects. One problem with this is that STL does not clean up any heap memory that you allocated. For that take a look at Boost Pointer Container Library or smart pointers.