2

我有一个 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),
    ...
);
4

2 回答 2

1

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);
} 
于 2017-03-02T00:15:36.287 回答
1

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);
}
于 2017-03-02T17:32:10.590 回答