Hacker News new | ask | show | jobs
by secondcoming 2021 days ago
Just yesterday I had to wrap up offsetof in a macro for use in some pseudo-reflection code

    #define MEMBER(C, M) { offsetof(C, M), sizeof(C::M) }
I couldn't figure out nice a way to do this without the preprocessor. The best I came up with was to use a lambda:

    [] (const C& c) { return std::cref(c.m); }
But these are stored in a std::map which means I have to use function pointers or accept the overhead of std::function
1 comments

Rather than storing the offset within the struct, you could store a type-erased pointer to data member:

    struct M {
        std::byte M::*p;
        std::size_t l;
        template<class C, class T>
        M(T C::*e) : p{reinterpret_cast<std::byte M::*>(e)}, l{sizeof(T)} {}
    };
Also there are ways (not necessarily legal) to convert a pointer to data member to an offset; see the proposal http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p090...