Sam*_*ett 3 c++ template-meta-programming boost-hana
如果我有变体,就像这样:
using my_variant = boost::variant<int, bool, std::string>;
Run Code Online (Sandbox Code Playgroud)
有没有一种简单的方法可以将变量可以包含的类型提取到Boost.Hana元组中,以便满足以下条件:
using boost::hana::type;
static_assert(std::is_same<my_tuple, boost::hana::tuple<type<int>, type<bool>, type<std::string>>>{});
Run Code Online (Sandbox Code Playgroud)
以下内容适用于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>, "");
Run Code Online (Sandbox Code Playgroud)
什么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和朋友的特殊性,你应该尽可能地坚持下去,否则你会发现Hana真的很笨重(因为没有考虑到这一点).