Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

struct template type deduction from member address

I'm writing a static reflection library for a game engine (it's a free time personal project). Note that I'm using C++17.

Instead of directly storing the class member offsets, I'm storing the member address using this template struct:

template<class ClassType, typename MemberType, MemberType ClassType::*AddressValue>
struct MemberAddress
{
    typedef MemberType ClassType::* Type;
    static constexpr const Type _value = AddressValue;
};

How can I re-write it in order to make it self-deduce ClassType and MemberType, by just writing the member address? I mean, I want to write:

struct Vec3 { float x, y, z = 0.f};

typedef MemberAddress<&Vec3::x> MemberAddress_x

instead of

typedef MemberAddress<Vec3, float, &Vec3::x> MemberAddress_x

Ideally the solution would also use C++14 and C++11.

like image 819
Antonio Cantarella Avatar asked Aug 13 '26 23:08

Antonio Cantarella


1 Answers

You are lucky to have C++17, in earlier versions it would be impossible since the solution hinges upon auto template parameter. But with it it looks like that:

template<class T, T val>
struct MemberAddrHelper;

template<class ClassType, typename MemberType, MemberType ClassType::*AddressValue>
struct MemberAddrHelper<MemberType ClassType::*, AddressValue> {
    typedef MemberType ClassType::* Type;
    static constexpr const Type _value = AddressValue;
};

template<auto addr>
using MemberAddr = MemberAddrHelper<decltype(addr), addr>;

struct foo {
    int bar;
};

using baz = MemberAddr<&foo::bar>;
like image 50
bartop Avatar answered Aug 16 '26 16:08

bartop



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!