I have class containing an std::set of boost::weak_ptr<T>. I have two functions begin() and end() that return an iterator to the container. However, I don’t want clients to be able to modify T. Simply returning a const_iterator won’t work, because the T pointed to by the boost::weak_ptr will be editable.
What I want to do is return a const_iterator to std::set<boost::weak_ptr<T const> >. Casting from std::set<boost::weak_ptr<T> >::const_iterator does not work. Is there any way to get the behaviour I want?
You can write a transform iterator to convert the
weak_ptr<T>to aweak_ptr<const T>. Since you’re already using Boost, you can useboost::transform_iterator:If you don’t want to use
boost::transform_iterator, it is a straightforward task to write your own. I showed how to do this in an answer to another question.