Reputation: 107
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.
Upvotes: 3
Views: 131
Reputation: 10315
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>;
Upvotes: 2