fork(1) download
  1. #include <iostream>
  2. #include <string>
  3. #include <boost/shared_ptr.hpp>
  4. #include <boost/make_shared.hpp>
  5. #include <boost/bimap.hpp>
  6. #include <boost/iterator/transform_iterator.hpp>
  7.  
  8. struct A
  9. {
  10. std::string data;
  11. A(const std::string& s) : data(s) {}
  12. };
  13.  
  14. typedef boost::bimap<unsigned int, boost::shared_ptr<A> > container_type;
  15. typedef container_type::left_map::const_iterator base_const_iterator;
  16.  
  17. template <typename T>
  18. struct makeIterConst : std::unary_function<base_const_iterator::value_type const &,
  19. std::pair<unsigned int const, boost::shared_ptr<T const> const> >
  20. {
  21. std::pair<unsigned int const, boost::shared_ptr<T const> const> operator()
  22. (base_const_iterator::value_type const & orig) const
  23. {
  24. std::pair<int const, boost::shared_ptr<T const> const> newPair(orig.first, boost::const_pointer_cast<T const>(orig.second));
  25. return newPair;
  26. }
  27. };
  28.  
  29. typedef boost::transform_iterator<makeIterConst<A>,
  30. base_const_iterator> const_iterator;
  31.  
  32. int main()
  33. {
  34. container_type m;
  35. boost::shared_ptr<A> p = boost::make_shared<A>("foo");
  36. m.insert( container_type::value_type(1, p));
  37.  
  38. // using regular iterator
  39. for( base_const_iterator left_iter = m.left.begin();
  40. left_iter != m.left.end();
  41. ++left_iter )
  42. {
  43. std::cout << left_iter->first << " --> " << left_iter->second->data << '\n';
  44. left_iter->second->data = "bar"; // compiles
  45. }
  46.  
  47. // using constified iterator
  48. for( const_iterator left_iter = boost::make_transform_iterator(m.left.begin(), makeIterConst<A>() );
  49. left_iter != boost::make_transform_iterator(m.left.end(), makeIterConst<A>() );
  50. ++left_iter )
  51. {
  52. std::cout << left_iter->first << " --> " << left_iter->second->data << '\n';
  53. // the following will give a compilation error, as expected
  54. // left_iter->second->data = "changed_foo";
  55. }
  56. }
  57.  
Success #stdin #stdout 0s 2868KB
stdin
Standard input is empty
stdout
1 --> foo
1 --> bar