I want to create a vector from Zero and this requires creating an iterator class as well, but I have this problem when I want to set a const iterator That's my vector
template < class T, class Alloc = std::allocator<T> > class vector {
public:
typedef T value_type;
typedef Alloc allocator_type;
typedef T* pointer;
typedef T const * const_pointer;
typedef T& reference;
typedef T const & const_reference;
typedef iterator<value_type> iterator;
typedef iterator<const value_type> const_iterator;
typedef reverse_iterator<iterator> reverse_iterator;
// typedef reverse_iterator<const_iterator> const_reverse_iterator;
typedef typename allocator_type::size_type size_type;
typedef typename allocator_type::difference_type difference_type;
and that's my iterator class
template <class T> class iterator {
protected:
T* m_ptr;
public:
typedef T value_type;
typedef value_type* pointer;
typedef value_type* const const_pointer;
typedef value_type& reference;
typedef value_type const & const_reference;
typedef std::ptrdiff_t difference_type;
iterator() : m_ptr(nullptr) {}
iterator(pointer ptr) : m_ptr(ptr) {}
iterator(const iterator &iter) {m_ptr = iter.m_ptr;}
The error:
./vector.hpp:17:29: error: expected member name or ';' after declaration specifiers
typedef iterator<const value_type> const_iterator;
How can I fix this?
CodePudding user response:
You're trying to redefine the template to a concrete type:
typedef iterator<value_type> iterator;
I suggest renaming the class template to something else, like iterator_impl
:
template <class T> class iterator_impl {
protected:
T* m_ptr;
public:
typedef T value_type;
typedef value_type* pointer;
typedef value_type* const const_pointer;
typedef value_type& reference;
typedef value_type const & const_reference;
typedef std::ptrdiff_t difference_type;
iterator_impl() : m_ptr(nullptr) {}
iterator_impl(pointer ptr) : m_ptr(ptr) {}
iterator_impl(const iterator_impl &iter) : m_ptr{iter.m_ptr} {}
};
Then this'll work:
template < class T, class Alloc = std::allocator<T> > class vector {
public:
typedef T value_type;
typedef Alloc allocator_type;
typedef T* pointer;
typedef T const * const_pointer;
typedef T& reference;
typedef T const & const_reference;
typedef iterator_impl<value_type> iterator;
typedef iterator_impl<const value_type> const_iterator;
typedef std::reverse_iterator<iterator> reverse_iterator;
// typedef reverse_iterator<const_iterator> const_reverse_iterator;
typedef typename allocator_type::size_type size_type;
typedef typename allocator_type::difference_type difference_type;
};