简体   繁体   English

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

[英]Boost.Hana: Transform tuple of values to tuple of corresponding types in constexpr context

Recently I had to write a transformation from a tuple of values to the (constexpr) tuple of the types of the values.最近我不得不编写一个从值元组到值类型的 (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>);

The solution I came up with uses hana::transform and hana::typeid_ in an unevaluated context to allow for the result to be constexpr.我想出的解决方案在未评估的上下文中使用hana::transformhana::typeid_以允许结果为 constexpr。 It relies on hana::type being default-constructible (as documented in hana::type_c ) and hana::tuple being default-constructible if all of the element types are.它依赖于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_)){};
};

If you know that values can be used with hana::transform directly then hana::to_tuple can be dropped (eg. std::array cannot be transformed directly).如果您知道values可以直接与hana::transform一起使用,则可以删除hana::to_tuple (例如std::array不能直接转换)。

This can be used to implement finding the common element type of a hana::tuple :这可用于实现查找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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM