C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Proposal: std::obj_from_dmbr

From: Marcin Jaczewski <marcinjaczewski86_at_[hidden]>
Date: Mon, 22 Aug 2022 12:27:16 +0200
niedz., 21 sie 2022 o 07:11 Walt Karas via Std-Proposals
<std-proposals_at_[hidden]> napisaƂ(a):
>
> In C++, there are two ways to use subobjects to build up an object, base classes and data members. A significant distinction is that, in a Standard-blessed way, you can derive (using static_cast) the address of the object from the address of a base class. This proposal implicitly asserts that this distinction is undesirable and unnecessary.
>
>
> I propose adding these two templates to the Standard Library:
>
>
> template <class Mbr, typename Obj>
> Obj & obj_from_dmbr(Mbr Obj::*mbr_ptr, Mbr &mbr);
>
>
> template <class Mbr, typename Obj>
> Obj * obj_from_dmbr(Mbr Obj::*mbr_ptr, Mbr *mbr);
>
>
> For mbr a reference/pointer to the indicated (by Mbr_ptr) data member of an object (of tclass Obj), these functions return a reference/pointer to the object. Their behavior is undefined if mbr does not actually refer/point to the indicated data member of an instance of Obj.
>
>
> Here is a model implementation: https://godbolt.org/z/1oM5rGPK8
>
>
> The effectiveness of this proposal is a bit hamstrung by unfortunate limitations with member pointers. For example, if array[] is an array within class C, I can't write &(C::array[i42]). But it would be possible to implement this proposal with a macro, where an invocation like:
>
>
> C *cp = OBJ_FROM_DMBR(C, array[i42], pointer_to_element_42_in_array);
>

I had some time ago a similar idea but not by using special functions
but by adding arithmetic operations to member pointers.

```
Obj* obj = mbr - &Obj::Mbr;
mbr == obj + &Obj::Mbr;
```

One benefit over function is that it better compose like:
```
mbr - &Obj::Mbr + &Obj::Foo;
```
It would also handle some use cases of `addressof` usage.

In case of array it could be done by:
```
(p - 42) - &Obj::array
```

>
> would work.
> --
> Std-Proposals mailing list
> Std-Proposals_at_[hidden]
> https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals

Received on 2022-08-22 10:27:28