c++ - Is it possible to reuse usual iterator to build const iterator? -


research

i found this old answer. i'd know if solution still effective or if there new, more effective way it.

background

lets suppose have iterator below (specifics don't matter, huge):

    class inorder_iterator : public std::iterator<std::forward_iterator_tag, token>     {         friend syntax_tree;          node* current_node;         std::stack<node*> prev_nodes;         //std::stack<node*> visited_nodes;         std::map<node*, bool> visited;     public:         inorder_iterator();          inorder_iterator& operator++();         inorder_iterator operator++(int);          token& operator*();         const token& operator*() const;          token* operator->();         const token* operator->() const;          friend bool operator==(const inorder_iterator lhs, const inorder_iterator rhs);         friend bool operator!=(const inorder_iterator lhs, const inorder_iterator rhs);      private:         inorder_iterator(node* current);         node* find_leftmost_node(node* from);     }; 

problem

implementations of member function declarations of reasonable size, reuse current iterator reduce code duplication.

idea

first idea came mind templatize on node type, pass const node make const iterator, sounds fishy

template <typename node> //replace every occurrence of node node // , use decltype(node.tk) instead of token everywhere 

also i'm not sure if use of const 1 of "const belongs implementation specifics" case.

a template way avoid code duplication. wouldn't leave type parameter open. i'd use boolean parameter fed std::conditional in order determine type:

template<bool isconst> class iter_impl {   using value_type = std::conditional_t<isconst, node const, node>; }; 

the 2 iterator types of container can either couple of aliases, or if want distinct types, couple of classes inherit template. so:

struct const_iterator : iter_impl<true> {}; struct iterator : iter_impl<false> {}; 

the benefit of using 2 new classes, can define converting constructor const_iterator allows build non const iterator. akin standard library's behavior.

also i'm not sure if use of const 1 of "const belongs implementation specifics" case.

the fact use const node indeed implementation detail. long gives documented type behavior (an iterator const member of container) wouldn't stress on this.


Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -