c++ - 使用模板参数定义 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 结构?
解决方案
我在这里找到了解决方案: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)
);
};
推荐阅读
- phpunit - #PHPUnit 测试简单代码在此链接:https://phpunit.de/getting-started/phpunit-8.html
- google-sheets - 根据一个标准拉取范围
- r - R如何从列表中提取数据集?
- python - 如何使用张量初始化内核
- java - 在 Android 分页库中使用过滤器或搜索的最佳方式
- c - 为什么这个小 shellcode 在 C 程序中工作,但不是单独的?
- javascript - event.stopPropagation() 不适用于表单
- c# - 为 sharedDrive 中的用户插入权限
- ruby-on-rails - Ruby on Rails 应用程序在一段时间后返回 504 错误
- python - pd.merge :尝试合并具有相同列名的数据框