title: How to avoid code duplication implementing const and non-const iterators?
body: <p>I'm implementing a custom container with an STL-like interface.  I have to provide a regular iterator and a const iterator.  Most of the code for the two versions of the iterators is identical .  How can I avoid this duplication?</p>
  
  <p>For example, my container class is <code>Foo</code>, and I'm implementating <code>FooIterator</code> and <code>FooConstIterator</code>.  Both of the iterators have to provide methods like <code>operator++()</code> which are identical.</p>
  
  <p>My question is similar to <a href="https://stackoverflow.com/questions/123758/how-do-i-remove-code-duplication-between-similar-const-and-non-const-member-funct">How do I remove code duplication between similar const and non-const member functions?</a>, but the answer to that one is specific to const and non-const methods, especially accessors.  I don't see how that might generalize to the iterator problem.</p>
  
  <p>Should I have <code>FooIterator</code> derive from <code>FooConstIterator</code> and extend it with additional non-const methods?  That either leads to virtual methods or method hiding, which seem inappropriate here.</p>
  
  <p>Perhaps <code>FooIterator</code> should contain a <code>FooConstIterator</code>.  Although that approach does reduce implementation duplication, it seems to re-introduce a lot of boilerplate method definitions.</p>
  
  <p>Is there clever template technique for generating the two iterators from a single definition?  Or perhaps there's a way to--shudder--use the preprocessor to stamp out these nearly identical classes.</p>
  
  <p>I've tried looking at my local STL implementation to see how it handle this.  There are so many helper classes that I'm having trouble grokking the design, but it looks like the functionality is simply duplicated.</p>
  
  <p>In previous projects, my custom container was built on top of a standard STL container, so I didn't have to provide my own iterators.  That's not an option in this case.</p>