Skip to content

Instantly share code, notes, and snippets.

@giraphics
Created December 23, 2018 17:16
Show Gist options
  • Save giraphics/734d077e9492ca374712e50ac39af4a3 to your computer and use it in GitHub Desktop.
Save giraphics/734d077e9492ca374712e50ac39af4a3 to your computer and use it in GitHub Desktop.
Retrieving parent object from structure's member
// Example program
#include <iostream>
#include <string>
#include <cstddef>
#include <iostream>
using namespace std;
template <typename Owner, typename Tag>
struct offset_aware
{
Owner *owner()
{
return reinterpret_cast<Owner *>(
reinterpret_cast<char *>(this) - Tag::offset());
}
};
#define OFFSET_AWARE(Owner, name) \
struct name ## _tag { \
static ptrdiff_t offset() { \
return offsetof(Owner, name); \
} \
}; \
offset_aware<Owner, name ## _tag> name
struct foo
{
int x;
OFFSET_AWARE(foo, a);
OFFSET_AWARE(foo, b);
OFFSET_AWARE(foo, c);
int y;
};
int main()
{
foo f;
cout << "foo f = " << &f << endl
<< "f.a: owner = " << f.a.owner() << endl
<< "f.b: owner = " << f.b.owner() << endl
<< "f.c: owner = " << f.c.owner() << endl
<< "Size of foo = " << sizeof(foo) << endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment