1

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.

Daniel
  • 30,896
  • 18
  • 85
  • 139
  • 3
    do you really need a member pointer? That would be a pointer that can point either to `A::a` or to `A::b`, but if you merely need to point to `A::b` of some `B` instances, then a `int*` will do – 463035818_is_not_an_ai Oct 14 '19 at 15:14
  • 1
    related/dupe: https://stackoverflow.com/questions/3439074/nested-data-member-pointer-not-possible – NathanOliver Oct 14 '19 at 15:15
  • @formerlyknownas_463035818: I pass it in a template to be used with many instances, a pointer to memory is not really an option – Daniel Oct 14 '19 at 15:22

1 Answers1

1

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.

eerorika
  • 232,697
  • 12
  • 197
  • 326