C++ Logo

std-proposals

Advanced search

Re: Container.iterator_to for getting an iterator form the reference to value

From: Andrey Semashev <andrey.semashev_at_[hidden]>
Date: Thu, 13 Aug 2020 18:31:46 +0300
On 2020-08-13 17:58, Arthur O'Dwyer via Std-Proposals wrote:
> On Thu, Aug 13, 2020 at 9:57 AM Antony Polukhin via Std-Proposals
> <std-proposals_at_[hidden] <mailto:std-proposals_at_[hidden]>>
> wrote:
>
> There are useful functions container.iterator_to in Boost.Intrusive
> containers that could be adopted by the Standard Library.
>
> Assuming that the `value` is in the `container`, the call
> `container.iterator_to(value)` returns an iterator to that `value` in
> the container.
>
>
> This is implementable for `std::vector`.
> This is implementable for `std::list` and `std::forward_list`, if you
> are okay with the library relying on reinterpret_cast.
> This is implementable for `std::set` and `std::map`, if you are okay
> with the library relying on reinterpret_cast.
> This is implementable for `std::unordered_set` and `std::unordered_map`,
> if you are okay with the library relying on reinterpret_cast.
> This is not implementable for `std::deque` (at least not in O(1)).
>
> To implement `iterator_to` for anything except `vector`, you have to
> rely on a cast like this:
>
> struct Node {
> T t;
> Node *next;
> };
> Node *node_from_t(T *t) {
> return reinterpret_cast<Node *>(t);
> }
> int main() {
> Node n;
> assert(node_from_t(&n.t) == &n);
> }
>
> I'm not sure if this is well-defined. As long as `t` is the first member
> of `Node`, I think it might actually be well-defined; but I wouldn't bet
> money on it.
> Problem is, library implementors tend to be /*extremely*/ loath to rely
> on anything smelling of UB in their implementations.

There is always offsetof. Yes, the standard doesn't require it to work
in all cases, but (a) it should work in this case regardless of the type
T on any reasonable implementation and (b) the compiler could provide
__builtin_offsetof_that_actually_works.

Received on 2020-08-13 10:35:16