【问题标题】:Define Hana struct with template parameters使用模板参数定义 Hana 结构
【发布时间】:2018-05-01 00:05:03
【问题描述】:

有没有办法为 Hana 定义(调整)具有模板参数的结构?

canonical example 是一个非模板类,

#include <boost/hana/define_struct.hpp>
#include <string>

namespace hana = boost::hana;

struct Person {
    BOOST_HANA_DEFINE_STRUCT(Person,
        (std::string, name),
        (int, age)
    );
};

我们我尝试添加模板参数出现编译错误:

template<class S = std::string, class I = int>
struct Person {
    BOOST_HANA_DEFINE_STRUCT(Person<S, I>,
        (S, name),
        (I, age)
    );
};

我虽然因为使用逗号而失败,所以我尝试用decltype(Person&lt;S, I&gt;) 代替Person&lt;S,I&gt;

在 Boost.Fusion 中我们有 BOOST_FUSION_DEFINE_TPL_STRUCT,但我在 Hana 中找不到等价物。

如何使用模板参数定义 Hana Struct?

【问题讨论】:

    标签: c++ templates boost-fusion boost-hana


    【解决方案1】:

    我在这里找到了解决方案:https://boostorg.github.io/hana/group__group-Struct.html

    template<class S, class I>
    struct Person {
        S name;
        I age;
    
        struct hana_accessors_impl {
            static BOOST_HANA_CONSTEXPR_LAMBDA auto apply() {
                return boost::hana::make_tuple(
                    boost::hana::make_pair(BOOST_HANA_STRING("name"),
                    [](auto&& p) -> decltype(auto) {
                        return boost::hana::id(std::forward<decltype(p)>(p).name);
                    }),
                    boost::hana::make_pair(BOOST_HANA_STRING("age"),
                    [](auto&& p) -> decltype(auto) {
                        return boost::hana::id(std::forward<decltype(p)>(p).age);
                    })
                );
            }
        };
    };
    

    这引发了另一个问题,为什么 Hana 需要第一个参数?因为没有必要?

    顺便说一句,这也有效,这是我没有尝试开始的。 我不确定它是否普遍有效。

    template<class S, class I>
    struct Person {
        BOOST_HANA_DEFINE_STRUCT(Person,
            (std::string, name),
            (int, age)
        );
    };
    

    【讨论】:

    • 宏可能需要类名作为指向成员的指针(例如 &Person::name)。
    • @JasonRice,这可以解释为什么它不应该有额外的模板参数。其实应该和里面的模板参数一起工作。我不知道。
    • 它必须是模板的实例化类型,例如Person&lt;string, int&gt;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多