Hi,
Suppose I have a list which contains pointers. I want the pointer got
by dereferencing the iterator be a pointer pointing to a const object.
But std::list<const T*>::const_iterator doens't give me this
capability. So I want std::list<T*>::iterator.
However, the container is of type std::list<T*>. How to get
std::list<const T*>::iterator?
How about
reinterpret_cast<std::list<const T *> &>(original_list)
to interpret the list as a list of const T * pointers? It's a hack, but
innocous enough. The templates should be binary compatible, so you are
down to some obscure undefined behavior related to aliasing.
Or else you could implement an iterator proxy object which wraps around
an existing iterator but adds const qualification to any extracted
pointers.
converting_iter<const T *, std::list<T *>::iterator>
cui = original_list.begin();
The converting_iter template has two parameters: the iterator type to
be wrapped, and the type that the extracted values should be cast to.
Of course converting_iter has a converting constructor that takes a
reference to the iterator type being wrapped, so it can swallow the
object being proxied. Supporting assigment from that type might be
handy too.
It has to proxy all of the iter operations and pass them to the
captured object: things like ++, and so on. The ones that pull out a T
* are intercepted and wrapped with a static_cast<const T *>.
This could be used in other ways, e.g.
converting_iter<float, std::vector<int>::iterator>
would give you an converting iterator type that wraps iterators for a
std::vector<int>, with an interator that pulls out the values converted
to float.