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
I did implement exactly the same thing a while ago in my root_ptr:
https://github.com/philippeb8/root_ptr/blob/master/include/boost/smart_ptr/detail/classof.hpp#L88
But I don't use reinterpret_cast, but just a sequence of
static_cast upcasts / downcasts.
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); would work.
|
|
|||||||
Le message ci-dessus,
ainsi que les documents l'accompagnant, sont destinés
uniquement aux personnes identifiées et peuvent contenir
des informations privilégiées, confidentielles ou ne
pouvant être divulguées. Si vous avez reçu ce message par
erreur, veuillez le détruire.This communication (and/or the attachments) is intended for named recipients only and may contain privileged or confidential information which is not to be disclosed. If you received this communication by mistake please destroy all copies. |
||||||||