C++ Logo


Advanced search

Re: std::iterator_static_cast & std::iterator_const_cast?

From: Brian Bi <bbi5291_at_[hidden]>
Date: Thu, 2 May 2019 09:34:25 -0500
I think we should have something slightly more general:

template <class Container>
auto std::unconstify_iterator(Container& c, const typename
Container::const_iterator& i) -> typename Container::iterator;

Here, `i` is required to be an iterator into `c`, or the behaviour is
undefined. The return value is a non-const iterator to the same element.
The logic is that if you have a const iterator into a non-const container,
then you have the right to modify the container and you have identified the
element you want to modify, so you should be entitled to get the
corresponding non-const iterator in O(1) time. You could dereference the
iterator and const_cast the result instead, but that's ugly and makes a
safe operation look unsafe.

This would obviate the need for std::iterator_const_cast in most cases,
since in most cases you are trying to do something safe, and this is what
it is.

Then, if you really want to convert the iterator unsafely, you can
const_cast the *container* and then call unconstify_iterator.

On Thu, May 2, 2019 at 9:16 AM sotrdg sotrdg via Std-Proposals <
std-proposals_at_[hidden]> wrote:

> Why does the standard not have std::iterator_const_cast? There is no
> standard way to convert type like std::deque<std::size_t>::const_iterator
> to std::deque<std::size_t>::iterator vice versa or
> std::deque<std::size_t>::const_reverse_iterator to
> std::deque<std::size_t>:: reverse_iterator
> std::iterator_static_cast can also solve the definition problem of
> contiguous_iterator, if an iterator T can std::iterator_static_cast to
> typename std::iterator_traits<T>::pointer and void*, then it is a
> contiguous_iterator.
> Sent from Mail <https://go.microsoft.com/fwlink/?LinkId=550986> for
> Windows 10
> --
> Std-Proposals mailing list
> Std-Proposals_at_[hidden]
> http://lists.isocpp.org/mailman/listinfo.cgi/std-proposals

*Brian Bi*

Received on 2019-05-02 09:36:18