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

前端 未结 6 1079
借酒劲吻你
借酒劲吻你 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:14

    Arthor O'Dwyer is answering this in detail in his blog post: https://quuxplusone.github.io/blog/2018/12/01/const-iterator-antipatterns/

    In essence,

    template
    class MyIterator {
        int *d_;
    public:
        MyIterator(const MyIterator&) = default;  // REDUNDANT BUT GOOD STYLE
    
        template>
        MyIterator(const MyIterator& rhs) : d_(rhs.d_) {}  // OK
    };
    using Iterator = MyIterator;
    using ConstIterator = MyIterator;
    };
    

    Also, add static_assert(std::is_trivially_copy_constructible_v); to your code, to make sure your iterators stay trivially copy constructible:

    Conclusion: If you are implementing your own container iterators — or any other pair of types with this “one-way implicit converting” behavior, such as the Networking TS’s const_buffers_type and mutable_buffers_type — then you should use one of the patterns above to implement converting constructors without accidentally disabling trivial copyability.

提交回复
热议问题