简体   繁体   中英

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.

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>;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM