【问题标题】:boost hana: create a map from a set and a default valueboost hana:从集合和默认值创建地图
【发布时间】:2017-03-01 17:11:46
【问题描述】:

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

【问题讨论】:

    标签: c++ dictionary boost set boost-hana


    【解决方案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);
    } 
    

    【讨论】:

      【解决方案2】:

      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);
      }
      

      【讨论】:

        猜你喜欢
        • 2023-03-28
        • 1970-01-01
        • 2018-12-02
        • 2020-04-09
        • 1970-01-01
        • 1970-01-01
        • 2020-08-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多