C++ Logo

std-proposals

Advanced search

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

From: sotrdg sotrdg <euloanty_at_[hidden]>
Date: Thu, 2 May 2019 14:39:19 +0000
template <class Container>
auto std::unconstify_iterator(Container& c, const typename Container::const_iterator& i) -> typename Container::iterator;

Adding container as parameter is a bad idea since I might not able to get the container object, for example, writing algorithms.

Casts are always unsafe. No matter what cast you are using.

I do believe std::iterator_static_cast and std::iterator_const_cast is useful, especially dealing with C apis.

Sent from Mail<https://go.microsoft.com/fwlink/?LinkId=550986> for Windows 10

________________________________
From: Brian Bi <bbi5291_at_[hidden]>
Sent: Thursday, May 2, 2019 10:34:25 PM
To: std-proposals_at_[hidden]
Cc: sotrdg sotrdg
Subject: Re: [std-proposals] std::iterator_static_cast & std::iterator_const_cast?

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]<mailto: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]<mailto:Std-Proposals_at_[hidden]>
http://lists.isocpp.org/mailman/listinfo.cgi/std-proposals
--
Brian Bi

Received on 2019-05-02 09:40:59