jeudi 19 novembre 2020

Pointer to a member's member

C++ allows one to define pointers to members of a class like:

struct A
{
  int i;
};

void a()
{
  int A::*p = &A::b::j;
}

but what if I want a pointer to a member that's on a deeper "level" like this?

struct A
{
  int i;
  struct B{int j;};
  B b;
};

void a()
{
  int A::*p = &A::b::j;
}

Theoretically it seems that if pointer to members are compiled to offets from the start of the object this could have been easily supported by the language although things like virtual/diamond inheritance would probably make this far too complicated

What's the easiest way to achieve that without performance penalties or undefined behaviour?

My first idea was to just use an offset and work with raw pointers on the object but that seems like it might not be defined behaviour and would also make it impossible for the compiler to detect if I'm pointing to actual fields with the correct type

Aucun commentaire:

Enregistrer un commentaire