Skip to content

Instantly share code, notes, and snippets.

@Liam0205
Created January 10, 2018 10:43
Show Gist options
  • Save Liam0205/78725c33de5545335ee81235cd9f5f0e to your computer and use it in GitHub Desktop.
Save Liam0205/78725c33de5545335ee81235cd9f5f0e to your computer and use it in GitHub Desktop.
A customized `offsetof` implement, in modern C++.
#include <stdio.h>
#define offsetof(s, m) reinterpret_cast<size_t>(&reinterpret_cast<const volatile char&>(\
static_cast<s*>(nullptr)->m))
struct S {
char c;
double d;
char cc;
};
int main(void) {
printf("the first element is at offset %zu\n", offsetof(struct S, c));
printf("the double is at offset %zu\n", offsetof(struct S, d));
printf("the third element is at offset %zu\n", offsetof(struct S, cc));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment