作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
如果我有一个变体,像这样:
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>>>{});
最佳答案
以下将适用于 develop
(从 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, bool, 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, bool, std::string>, "");
什么 e13d826确实添加了对 mpl::list
的支持;只有mpl::vector
之前支持过,boost::variant<>::types
是 mpl::list
.这就是为什么我的回答花了一段时间才出来;我正在实现 :-)。
编辑
我没有解释为什么要使用 constexpr auto my_tuple = ...
而不是 using my_tuple = decltype(...)
.好吧,原因很简单,因为知道 my_tuple
的类型并不是真的有用,因为你不能依赖它。事实上,如果您查看 hana::type
的文档,上面写着你不能依赖hana::type<T>
是任何具体的。这有充分的理由,但从可用性的角度来看,这意味着您不能依赖 hana::tuple<hana::type<...>, ...>
的类型。也可以是任何特定的。在进行类型级计算时,更喜欢值级编码(因此 auto my_tuple = ...
)而不是类型级编码。这是 Hana 相对于 MPL 和 friend 的特殊性,你应该尽可能地坚持它,否则你会发现 Hana 真的很笨拙(因为没有考虑到这一点)。
关于c++ - 花 : How do I create a tuple of types from a variant?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33679142/
我是一名优秀的程序员,十分优秀!