Skip to content

Instantly share code, notes, and snippets.

@roachsinai
Forked from codehz/c++property.cpp
Created October 16, 2023 11:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save roachsinai/48c55f558d526b51e88bafec33ade99d to your computer and use it in GitHub Desktop.
Save roachsinai/48c55f558d526b51e88bafec33ade99d to your computer and use it in GitHub Desktop.
#include <cstddef>
#include <cstdlib>
template <typename R, auto getter, auto setter, size_t (*offset)()>
struct property {
inline R *self() {
return reinterpret_cast<R *>(reinterpret_cast<size_t>(this) - offset());
}
inline operator auto() { return (self()->*getter)(); }
inline void operator=(auto t) { (self()->*setter)(t); }
};
#define def_property(C, N, getter, setter) \
inline constexpr static size_t _##N##_offset() { return offsetof(C, N); } \
[[no_unique_address]] property<C, &C::getter, &C::setter, \
C::_##N##_offset> \
N
struct X {
private:
int get_a();
void set_a(int);
public:
int padding[25];
def_property(X, a, get_a, set_a);
};
static_assert(sizeof(X) == 100, "!!");
int test(X &x, int val) {
x.a = val;
return x.a;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment