从hana :: tuple_t到hana :: tuple

时间:2017-01-10 17:02:27

标签: c++ boost-hana typelist

我有hana::tuple_t<int, char, double, float>,我想用它来创建hana::tuple<int, char, double, float>

我认为使用hana::to<hana::tuple_tag>会将hana::tuple_t<int, char, double, float>转换为hana::tuple<int, char, double, float>;但事实并非如此,因为以下情况总是失败:

auto oType = hana::tuple_t<int, char, double, float>;

BOOST_HANA_CONSTANT_ASSERT(
    hana::to<hana::tuple_tag>(oType)
    ==
    hana::make_tuple(1, 'C', 1.0, 1.0f)
);

我也试过使用hana::transform,但没有运气(虽然我怀疑我做错了):

auto vecs = hana::transform(typeList, [](auto t) {
    return typename decltype(t)::type{};
});

那么,我如何将hana :: tuple_t变成hana :: tuple?

2 个答案:

答案 0 :(得分:4)

hana::tuple_t只是一个模板变量,本身已经是hana::tuple,因此转换为hana::tuple不会改变任何内容。

template <typename ...T>
constexpr hana::tuple<hana::type<T>...> tuple_t{};

正如评论中所提到的,您对hana::transform的调用默认初始化每个成员,因此您可以期望整数类型的值为0。

此外,您正在使用BOOST_HANA_CONSTANT_ASSERT来检查编译时值。原始intchardoublefloat值不会是constexpr

BOOST_HANA_RUNTIME_ASSERT适用于运行时值:

#include <boost/hana.hpp>

namespace hana = boost::hana;

constexpr auto types = hana::tuple_t<int, char, double, float>;

struct init_from_type_fn
{
  template <typename Type>
  constexpr auto operator()(Type) const
  {
    return typename Type::type{};
  }
};

constexpr init_from_type_fn init_from_type{};

int main()
{
  BOOST_HANA_RUNTIME_ASSERT(
    hana::equal(
      hana::transform(types, init_from_type),
      hana::make_tuple(0, '\0', 0.0, 0.0f)
    )
  );
}

答案 1 :(得分:3)

我相信你真正想要的是

#include <boost/hana.hpp>
namespace hana = boost::hana;

constexpr auto types = hana::tuple_t<int, char, double, float>;
using Tuple = decltype(hana::unpack(types, hana::template_<hana::tuple>))::type;
// Tuple is hana::tuple<int, char, double, float>
// Now you can create such a tuple as you wish:
Tuple ts{1, 'x', 2.2, 3.4f};

hana::template_hana::metafunction之类的内容正是为了简化类型的互操作而构建的。