mercredi 14 décembre 2022

C++ class/struct member offset as constexpr?

The following construct in main() retrieves a class member's offset at runtime:

struct Base
{
  virtual ~Base() = default;
};

struct Cls : public virtual Base
{
  int a, b;
};



int main()
{
  int Cls::* ptr = &Cls::a;

  unsigned long offset = *reinterpret_cast<unsigned long*>(&ptr);
}

The class layout is determined at compile time and doesn't change. So, it would be beneficial to make this a constexpr.

Unfortunately, the above assignment requires an lvalue.

How can I get the same result using a constexpr?

Aucun commentaire:

Enregistrer un commentaire