3

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

我认为 usinghana::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?

4

2 回答 2

4

我相信你在这里真正想要的是

#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的东西正是为了使这种与类型的互操作变得容易而构建的。

于 2017-01-11T06:57:33.387 回答
4

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

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

如评论中所述,您对hana::transformdefault 的调用会初始化每个成员,因此您会期望诸如 0 之类的整数类型的值。

此外,您正在使用BOOST_HANA_CONSTANT_ASSERTwhich 检查编译时值。Raw int, char,doublefloatvalues 不会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)
    )
  );
}
于 2017-01-10T17:48:27.727 回答