加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – Hana:如何从变体创建类型元组?

发布时间:2020-12-16 10:12:07 所属栏目:百科 来源:网络整理
导读:如果我有变体,就像这样: using my_variant = boost::variantint,bool,std::string; 有没有一种简单的方法可以将变量可以包含的类型提取到Boost.Hana元组中,以便满足以下条件: using boost::hana::type;static_assert(std::is_samemy_tuple,boost::hana::tu
如果我有变体,就像这样:

using my_variant = boost::variant<int,bool,std::string>;

有没有一种简单的方法可以将变量可以包含的类型提取到Boost.Hana元组中,以便满足以下条件:

using boost::hana::type;
static_assert(std::is_same<my_tuple,boost::hana::tuple<type<int>,type<bool>,type<std::string>>>{});

解决方法

以下将适用于开发(自 e13d826起):

#include <boost/hana.hpp>
#include <boost/hana/ext/boost/mpl.hpp>
#include <boost/variant.hpp>
#include <string>
namespace hana = boost::hana;


using my_variant = boost::variant<int,std::string>;

constexpr auto my_tuple = hana::to<hana::tuple_tag>(my_variant::types{});

// Note:
// In general,don't use std::is_same to compare hana::tuple; use == in
// because it will also work if the tuple contains hana::basic_types.
static_assert(my_tuple == hana::tuple_t<int,std::string>,"");

e13d826所做的是添加对mpl :: list的支持;之前只支持mpl :: vector,而boost :: variant<> :: types是一个mpl :: list.这就是我的回答需要一段时间的原因;我正在实施:-).

编辑

我没有解释为什么我使用constexpr auto my_tuple = …而不是使用my_tuple = decltype(…).嗯,原因很简单,因为知道my_tuple的类型并不是很有用,因为你不能依赖它.实际上,如果你看一下hana :: type的文档,那就写出你不能依赖hana :: type< T>具体是什么.这有很好的理由,但从可用性的角度来看,这意味着你不能依赖hana :: tuple< hana :: type< ...>,…>的类型.任何具体的事情.在进行类型级计算时,首选值级编码(因此自动my_tuple = …)进行类型级编码.这是Hana对MPL& amp;的特异性.朋友们,你应该尽可能地坚持下去,否则你会发现Hana真的很笨重(因为没有记住这一点).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读