0

As a C++ newbie so far, my experience with overloading has been limited to copy, move assignment operators and well as I/O stream operators.

I now have to create a iterator for a parse tree node class, which means I have to overloading the following:

  1. ==
  2. *(dereference operator)
  3. ++
  4. --
  5. >=

I have been scouring the internet as well as several C++ books , but so far I nothing suitable to my particular case ( i.e. without reference to templates), however I have learn that the increment and decrement operators need to overloaded "twice" for both the postfix and prefix case

Could someone please explain how one would do this as well as the reasoning behind

Thank you :)

I apologise if it am being off topic.

TemplateRex
  • 69,038
  • 19
  • 164
  • 304

1 Answers1

1

You might want to take a look at the boost::iterator_facade from the Boost.Iterator library.

This will let you define member functions equal(), derefence(), increment(), decrement(), advance() and distance(). From these members, the library will then generate ==, !=, *, ++, --, +=, -=, [] and the relational operators <, >, <=, >= for you.

You can also define this by hand, but as you noted, there is much code duplication (equality and inequality, pre- and post-increment). Furthermore, an iterator also needs access to certain typedefs and carefully defined return types and lifetime management of temporaries in order to play nice with the Standard Library. The Boost.Iterator will take care of all that detail for you in a straightforward manner.

There is a worked example for a linked-list iterator that you can try to adapt into a tree iterator.

Note: it is not necessary to define a template yourself, but the iterator facade itself is a template, that you can then instantiate with the particular type of your tree class.

TemplateRex
  • 69,038
  • 19
  • 164
  • 304