How to avoid code duplication implementing const and non-const iterators?

前端 未结 6 1064
借酒劲吻你
借酒劲吻你 2020-11-29 18:30

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 it

6条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-29 19:06

    You can use CRTP and a common base to "inject" methods (but you still have to duplicate ctors in current C++), or just use the preprocessor (no shuddering required; handles ctors easily):

    struct Container {
    
    #define G(This) \
    This operator++(int) { This copy (*this); ++*this; return copy; }
    // example of postfix++ delegating to ++prefix
    
      struct iterator : std::iterator<...> {
        iterator& operator++();
        G(iterator)
      };
      struct const_iterator : std::iterator<...> {
        const_iterator& operator++();
        G(const_iterator)
      };
    
    #undef G
    // G is "nicely" scoped and treated as an implementation detail
    };
    

    Use std::iterator, the typedefs it gives you, and any other typedefs you might provide to make the macro straight-forward.

提交回复
热议问题