Pointer to member compounding

Viewed 68

I have two structs

struct A
{
    int a, b;
};
struct B
{
    A c, d;
};

I would like to get a pointer to the member b inside d.

&B::d.b; // int B::*

The closest I could get is getting the offset of it.

offsetof(B, d.b) // size_t

But this has no size or type information, so the best I could do is make a macro that passes the offset and type together, but not as int B::*.
Is there any standard solution to this? Is there any non standard solution to this?
On the nonstandard direction I was thinking of making a template that would be used like T<&B::d, &A::b> and would reinterpret the offsets and add them together, but I'm not sure how to do the reinterpret part.
I'm using c++17 with the latest Xcode clang on macOS.

1 Answers

You could use two member pointers:

int A::* foo = &A::b;
A B::* bar = &B::d;

B objB;
int& db = objB.*bar.*foo;

Downside is that each offset is stored separately, which is unnecessarily inefficient if it is done at runtime. Should be fine for compile time metaprogramming though.

Related