首页 > 解决方案 > 使用模板参数定义 Hana 结构

问题描述

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

典型的例子是一个非模板类,

#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<S, I>)代替Person<S,I>.

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

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

标签: c++templatesboost-fusionboost-hana

解决方案


我在这里找到了解决方案: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)
    );
};

推荐阅读