C++ Logo

std-proposals

Advanced search

[std-proposals] Proposal: std::obj_from_dmbr

From: Walt Karas <wkaras_at_[hidden]>
Date: Sun, 21 Aug 2022 05:11:15 +0000 (UTC)
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);


would work.

Received on 2022-08-21 05:11:19