Boost.Hana。在constexpr上下文中,将元组的值转换为相应类型的元组。

问题描述 投票:0回答:1

最近,我不得不写一个从值的元组到值的类型的(constexpr)元组的转换。

namespace hana = boost::hana;

// we have this (not neccessarily constexpr)
auto value_tuple = hana::make_tuple(1, 'a');

// we want this (must be constexpr)
constexpr auto type_tuple = hana::make_tuple(hana::type_c<int>, hana::type_c<char>);
c++ types tuples constexpr boost-hana
1个回答
0
投票

我想到的解决方案是使用 hana::transformhana::typeid_ 在一个未评价的上下文中,允许结果是constexpr.它依靠的是 hana::type 是默认可构造的(如在 hana::type_c)和 hana::tuple 如果所有的元素类型都是默认可构造的。

constexpr auto to_types = [](auto values) {
  namespace hana = boost::hana;
  return decltype(hana::transform(
      hana::to_tuple(std::declval<decltype(values)>()), hana::typeid_)){};
};

如果你知道 values 可与 hana::transform 然后 hana::to_tuple 可以放弃(例如 std::array 不能直接转换)。)

这可以用来实现寻找一个普通元素类型的 hana::tuple:

constexpr auto to_common_type = [](auto types) {
  namespace hana = boost::hana;
  return hana::unpack(types, hana::template_<std::common_type_t>);
};

using value_type =
    typename decltype(to_common_type(to_types(values)))::type;
© www.soinside.com 2019 - 2024. All rights reserved.