6

What are the best practices to avoid code duplication when implementing class pairs such as iterator and const_iterator or similar?

  • Does one usually implement iterator in terms of const_iterator using lots of const_casts?
  • Does one employ some sort of traits class and end up defining both iterator and const_iterator as different instantiations of a common template?

This seems like a common enough problem to have a canonical solution but I have failed to find any articles dedicated to that.

Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
Armen Tsirunyan
  • 130,161
  • 59
  • 324
  • 434
  • Sorry, too broad. Many different approaches. Inheritance. Templates. There is no universally agreed-upon "best practice". Each individual case varies. – Sam Varshavchik Nov 08 '16 at 13:41
  • I prefer a template class parametrized by `value_type`, `pointer_type`, `reference_type`. For example: `template class CustomIterator {};` `typedef CustomIterator iterator_type;` `typedef CustomIterator const_iterator_type;` – Narek Atayan Nov 08 '16 at 13:56
  • 1
    http://stackoverflow.com/questions/2150192/how-to-avoid-code-duplication-implementing-const-and-non-const-iterators – Ciro Santilli OurBigBook.com Dec 23 '16 at 07:37

1 Answers1

2

I don't have any experience with implementing iterators, although I think this is similar to other projects. Refactor common code, etc.

Looking at GNU libstdc++'s implementation of std::vector::iterator

#include <bits/stl_iterator_base_funcs.h>
// ...
template ... class vector : ... {
    typedef __gnu_cxx::__normal_iterator<pointer, vector> iterator;
    typedef __gnu_cxx::__normal_iterator<const_pointer, vector> const_iterator;
};
Olaf Dietsche
  • 72,253
  • 8
  • 102
  • 198