boost hana:从一个集合和一个默认值创建一个地图

boost hana: create a map from a set and a default value

我有一个 boost::hana::set 类型,想用它创建一个映射,其中的值为布尔值。

// I have a hana set:
auto my_set = hana::make_set(hana::type_c< int >, hana::type_c< float > ...);

// and want to transform it to a map with a given runtime value as values:
auto wanted_map = hana::make_map(
    hana::make_pair(hana::type_c< int >, false),
    hana::make_pair(hana::type_c< float >, false),
    ...
);

hana::sethana::Foldable 所以你可以使用 hana::unpack。考虑这个例子:

#include <boost/hana.hpp>

namespace hana = boost::hana;


int main() {
  constexpr auto make_pair_with = hana::curry<2>(hana::flip(hana::make_pair));

  auto result = hana::unpack(
    hana::make_set(hana::type_c< int >, hana::type_c< float >),
    hana::make_map ^hana::on^ make_pair_with(false)
  );

  auto expected = hana::make_map(
    hana::make_pair(hana::type_c< int >, false),
    hana::make_pair(hana::type_c< float >, false)
  );

  BOOST_HANA_RUNTIME_ASSERT(result == expected);
} 

Jason 的回答是完美的,但这里使用 lambda 来做同样的事情(我通常觉得它更具可读性):

#include <boost/hana.hpp>
namespace hana = boost::hana;


int main() {
  auto types = hana::make_set(hana::type_c< int >, hana::type_c< float >);
  auto result = hana::unpack(types, [](auto ...t) {
    return hana::make_map(hana::make_pair(t, false)...);
  });

  auto expected = hana::make_map(
    hana::make_pair(hana::type_c< int >, false),
    hana::make_pair(hana::type_c< float >, false)
  );

  BOOST_HANA_RUNTIME_ASSERT(result == expected);
}