Created
December 23, 2018 17:16
-
-
Save giraphics/734d077e9492ca374712e50ac39af4a3 to your computer and use it in GitHub Desktop.
Retrieving parent object from structure's member
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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