从 hana::tuple_t 到 hana::tuple

Going from hana::tuple_t to hana::tuple

我有一个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?

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

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

如评论中所述,您对 hana::transform default 的调用会初始化每个成员,因此对于整型类型,您会期望诸如 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, '[=11=]', 0.0, 0.0f)
    )
  );
}

我相信你真正想要的是

#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 之类的东西正是为了简化与类型的互操作而构建的。