9

I'm trying to create an iterator which only can dereference to real value types, not to references. Is this possible using boost::iterator_facade, or does it require me to have values that can be returned by adress\reference.

To be more specfic, my iterator returns a std::pair of references, which means my iterators value_type is not stored anywhere, but created on the fly on dereferencing (like std::map::iterator).

Viktor Sehr
  • 12,825
  • 5
  • 58
  • 90

1 Answers1

14

Yes, thing you want is possible. Please, take a look at boost/iterator_facade.hpp (example is for Boost lib of version 1.49.0 but it is ok for its new distributions also):

  template <
    class Derived
  , class Value
  , class CategoryOrTraversal
  , class Reference   = Value&
  , class Difference  = std::ptrdiff_t
>
class iterator_facade

Template argument Reference is the key. You should just specify Reference when deriving from boost::iterator_facade. For example, your code can look like as the following:

template<typename value_type>
class custom_iterator
    :    public boost::iterator_facade<
             custom_iterator<value_type>,
             value_type,
             boost::forward_traversal_tag,
             value_type
         >
{
    ...
    value_type dereference() const{ return value_type(...); }
    ...
};
Piotr Semenov
  • 1,761
  • 16
  • 24
  • Thank you for this answer, really helped me out. I do have a question though, before specifying the Reference template argument, I just tried returning the value. This compiled but gave me very strange results, such as pointers in my class becoming null at strange times. I suppose my question is, why did it compile at all? – FlamFace Apr 27 '16 at 10:56