【问题标题】:struct template type deduction from member address从成员地址推导struct模板类型
【发布时间】:2020-04-28 12:57:53
【问题描述】:

我正在为游戏引擎编写一个静态反射库(这是一个空闲时间的个人项目)。请注意,我使用的是 C++17。

我没有直接存储类成员偏移量,而是使用这个模板结构存储成员地址:

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

我怎样才能重写它以使其通过只写成员地址来自推导出ClassType和MemberType?我的意思是,我想写:

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

typedef MemberAddress<&Vec3::x> MemberAddress_x

而不是

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

理想情况下,该解决方案也将使用 C++14 和 C++11。

【问题讨论】:

  • 也许使用 constexpr 函数?具有这样的模式匹配/类型推断的功能是可能的。

标签: c++ templates template-meta-programming type-deduction


【解决方案1】:

你很幸运拥有 C++17,在早期版本中这是不可能的,因为解决方案取决于 auto 模板参数。但有了它,它看起来像这样:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-25
    • 2018-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多