#include #include #include class tree { public: virtual void grow() = 0; }; class oak : public tree { public: virtual void grow() { std::cout << "oak grows slowly" << std::endl; } }; class pine : public tree { public: virtual void grow() { std::cout << "pine grows quickly" << std::endl; } }; template< typename Container > class shared_iterator { public: typedef shared_iterator< Container > Self; typedef typename Container::iterator Iter; typedef typename Container::value_type Type; shared_iterator() : _iter() { } shared_iterator(const Self& rhs) : _iter(rhs._iter) { } shared_iterator(const Iter& iter) : _iter(iter) { } ~shared_iterator() { } shared_iterator& operator=(const Self& rhs) { if(this != &rhs) { _iter = rhs._iter; } return *this; } shared_iterator& operator=(const Iter& iter) { if(_iter != iter) { _iter = iter; } return *this; } bool operator!=(const Self& rhs) const { return (this != &rhs); } bool operator!=(const Iter& iter) const { return (_iter != iter); } // these two are where the magic happens Type& operator->() { return *_iter; } Type& operator*() { return *_iter; } // prefix shared_iterator& operator++() { _iter++; return *this; } // postfix shared_iterator& operator++(int) { Self self = *this; _iter++; return self; } private: Iter _iter; }; int main(int argc, char* argv[]) { typedef std::list< boost::shared_ptr< tree > > list_t; list_t forest; forest.push_back(boost::shared_ptr< tree >(new oak)); forest.push_back(boost::shared_ptr< tree >(new pine)); for(shared_iterator< list_t > iter = forest.begin(); iter != forest.end(); ++iter) { iter->grow(); } return 0; }