Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice for avoiding code duplication while implementing iterator and const_iterator classes [closed]

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.

like image 702
Armen Tsirunyan Avatar asked Nov 08 '16 13:11

Armen Tsirunyan


1 Answers

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;
};
like image 120
Olaf Dietsche Avatar answered Nov 04 '22 02:11

Olaf Dietsche