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
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.