Compile errors on boost::iterator_facade

476 views Asked by At

I'm learning boost::iterator_facade. Here is an example code from a book:

#include <iostream>
#include <boost/iterator/iterator_facade.hpp>

   template<typename I,std::ptrdiff_t N = 2>   
    class step_iterator:
            public boost::iterator_facade<
            step_iterator<I>,   
            typename boost::iterator_value<I>::type const,  
            boost::single_pass_traversal_tag>   
    {
    private:
        I m_iter;   
    public:
        step_iterator(I x) :    
            m_iter(x){}
        step_iterator(step_iterator const& other):  
            m_iter(other.m_iter){}
        void operator=(step_iterator const& other)  
        {   m_iter = other.m_iter;  }
    private:
        friend class boost::iterator_core_access;   
        reference dereference() const  
        {   return *m_iter; }
        void increment()
        {   std::advance(m_iter,N); }   
        bool equal(step_iterator const& other) const    
        {   return m_iter == other.m_iter;}
    };

Here is the test code:

int main()
{
    char s[] = "12345678";  
    std::copy(s,s+8,    
              std::ostream_iterator<char>(cout));   
    cout<<endl;
    step_iterator<char*> first(s),last(s+8);
    std::copy(first,last,   
              std::ostream_iterator<char>(cout));   
    return 0;
}

However, I get the following compile error:

    'reference' does not name a type
 (perhaps 'typename boost::iterator_facade<step_iterator<I, 2>, const typename boost::iterator_value<Iterator>::type, boost::single_pass_traversal_tag, const typename boost::iterator_value<Iterator>::type&, int>::reference' was intended)

So I tried to replace 'reference' with step_iterator::reference, this time I get the following error:

type 'step_iterator<I, 2>' is not derived from type 'step_iterator<I, N>'
1

There are 1 answers

0
Marshall Clow On BEST ANSWER

Your dereference function needs to return a reference to an element of the underlying sequence.

I would use std::iterator_traits<I>::reference, so the code would look like:

    typename std::iterator_traits<I>::reference dereference() const  
    {   return *m_iter; }