Search code examples
c++classiteratorconst-iterator

When is it sufficient to declare const_iterator as a const iterator?


For example, I could define a container in a way similar to:

template <typename T>
class Example
{
public:
    using value_type = T;
    using iterator = value_type*;
    using const_iterator = const iterator;
    //etc
};

However, is it okay to do this with a user-defined iterator?

template<typename T>
class Example
{
public:
    using value_type = T;
    /*friend?*/ class iterator;
    using const_iterator = const iterator; //is this okay?
    //etc
};

A detailed explanation would be appreciated.


Solution

  • A const_iterator and a const iterator represent two different things. In each case, the const applies to something different: the object "pointed to" by the iterator in the first case, and the iterator itself in the second. So, it is never "sufficient" to use one for the other.

    In pointer speak (and pointers are iterators), this would be the difference between "pointer to const" and "const pointer".

    const int* it; // pointer to const int: a const_iterator
    int* it const; // const pointer to int: a const iterator
    

    You can even have const iterators to const, or const const_iterator:

    const int* it const;