fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <list>
  4. #include <iterator>
  5. #include <typeinfo>
  6.  
  7. template <typename Iterator>
  8. class const_iterator
  9. {
  10. public:
  11. typedef Iterator iterator_type;
  12. typedef typename std::iterator_traits<Iterator>::difference_type difference_type;
  13. // note: trying to add const to ...:reference or ..:pointer doesn't work,
  14. // as it's like saying T* const rather than T const* aka const T*.
  15. typedef const typename std::iterator_traits<Iterator>::value_type& reference;
  16. typedef const typename std::iterator_traits<Iterator>::value_type* pointer;
  17.  
  18. const_iterator(const Iterator& i) : i_(i) { }
  19. reference operator*() const { return *i_; }
  20. pointer operator->() const { return i_; }
  21. bool operator==(const const_iterator& rhs) const { return i_ == rhs.i_; }
  22. bool operator!=(const const_iterator& rhs) const { return i_ != rhs.i_; }
  23. const_iterator& operator++() { ++i_; return *this; }
  24. const_iterator operator++(int) const { Iterator i = i_; ++i_; return i; }
  25. private:
  26. Iterator i_;
  27. };
  28.  
  29. template <typename Const_Iterator>
  30. void f(const Const_Iterator& b__, const Const_Iterator& e__)
  31. {
  32. ::const_iterator<Const_Iterator> b{b__}, e{e__};
  33. // *b = 2; // if uncommented, compile-time error....
  34. for ( ; b != e; ++b)
  35. std::cout << *b << '\n';
  36. }
  37.  
  38. int main()
  39. {
  40. std::vector<int> v { 11, 22, 33 };
  41. f(v.begin(), v.end());
  42. }
Success #stdin #stdout 0s 3472KB
stdin
Standard input is empty
stdout
11
22
33