Skip to content

Instantly share code, notes, and snippets.

@kerrytazi
Created December 24, 2023 03:57
Show Gist options
  • Save kerrytazi/74ed6b8121ef91de388da26ff9b34ee4 to your computer and use it in GitHub Desktop.
Save kerrytazi/74ed6b8121ef91de388da26ff9b34ee4 to your computer and use it in GitHub Desktop.
static_assert(_offsetof_(MyClass, my_field) == 0, "my_field must be first field");
#pragma once
#ifdef _MSC_VER
#define _offsetof_(s, m) offsetof(s, m)
#else
namespace detail {
template<typename T> struct declval_helper { static T value; };
template<typename T, typename Z, Z T::*MPtr>
struct offset_helper {
using TV = declval_helper<T>;
char for_sizeof[
(char *)&(TV::value.*MPtr) -
(char *)&TV::value
];
};
template<typename T, typename Z, Z T::*MPtr>
constexpr size_t offset_of() {
return sizeof(offset_helper<T, Z, MPtr>::for_sizeof);
}
}
#define _offsetof_(s, m) vm::detail::offset_of<s, decltype(s::m), &s::m>()
#endif // _MSC_VER
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment