Flamefire
Flamefire

Reputation: 5807

Iterator traits with iterator that returns wrapper object

I want to design an iterator that returns a wrapper, like this:

        VarArgReference operator*() const
        {
            return VarArgReference(state_, stack_index_);
        }
        VarArgReference operator->() const
        {
            return VarArgReference(state_, stack_index_);
        }

Now I want to define the iterator traits, e.g. by deriving from std::iterator. What I know: This is an InputIterator (read only objects). But I want it also to support Random Access functionality.

So step by step: For InputIterator I need *i return "reference, convertible to value_type". So I can simply set reference=value_type=VarArgReference.

Next step is forward iterator. However http://en.cppreference.com/w/cpp/concept/ForwardIterator says "std::iterator_traits::reference must be exactly [...] const T& [for OutputIterator] (It is constant), (where T is the type denoted by std::iterator_traits::value_type)"

So what shall it be? Is my reference now really const VarArgReference&? This means I'd need to return that type , a const& to a rvalue. And when is the pointer used? Do I need to make it const VarArgReference* or just VarArgReference.

Additional question: ForwardIterator must by default constructible. This would mean that I need to initialize the state with something (invalid?) and probably check and catch that on dereference. Or is it simply undefined behaviour and I can omit the checks?

Note: C++98 and C++11 need to work with this, if this matters

Note2: Using std::iterator is deprecated in C++17 which suggest defining the nested typedefs explicitly (see comments). So deriving from std::iterator is only a possibility to define those, which should however not be used.

Upvotes: 0

Views: 121

Answers (0)

Related Questions