【问题标题】:Going from hana::tuple_t to hana::tuple从 hana::tuple_t 到 hana::tuple
【发布时间】:2017-01-10 17:02:27
【问题描述】:

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

【问题讨论】:

  • 默认初始化将产生一个值0,而不是1(或1.0,或'C')。您是否尝试过将其与元组 hana::make_tuple(0, '\0', 0.0, 0.0f) 进行比较?
  • 是的,我试过了。编译器错误:Severity static_assert failed "hana::to<:tuple_tag>(oType) == hana::make_tuple(0, 0.0, 0.0f)"

标签: c++ boost-hana typelist


【解决方案1】:

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

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

【讨论】:

  • 您提到了hana::metafunction 以及与类型的互操作,所以我认为这就是您用来朝相反方向发展的方向(从类型hana::tuple&lt;A,B,C&gt; 到值hana::type_t&lt;A,B,C&gt;)。你能详细说明你是如何做到这一点的吗?
【解决方案2】:

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

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

如 cmets 中所述,您对 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)
    )
  );
}

【讨论】:

  • 看起来问题出在带有 Clang 的 MSVC 上。它只是不喜欢这段代码,但它使用 Clang 在我的虚拟机上运行良好。
  • 错误是什么?也许它没有指定c++14?我不使用 MSVC,但我听说有人使用 Hana。
  • 这是一个clang frontend command failed due to signal use。根据我收集的信息,编译器在尝试将所有内容放在一起时会感到困惑。没有办法抛出-v afaik,所以我认为它是一堵砖墙。
  • Hana 的 wiki 有一些关于它的东西。希望对您有所帮助...github.com/boostorg/hana/wiki/Setting-up-Clang-on-Windows
猜你喜欢
  • 2017-09-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-07
相关资源
最近更新 更多