如何合并两个或更多的 Boost Fusion 映射?

3
我想从两个boost::fusion::map类型创建一个关联序列。其中一个映射中包含的类型可能存在于另一个映射中,如果是这种情况,则希望在生成的序列中仅保留具有该键的单个类型。也就是说,在连接后,我希望唯一。
传统的join操作似乎允许重复的键,因此它似乎不是解决方案。有人知道我该如何实现吗?
// Here is what I've got:
using namespace boost::fusion;
map<
  pair<int, int>,
  pair<double, int>> Map1;

map<
  pair<bool, int>,
  pair<double, int>> Map2;

// I want to join Map1 with Map2 such that I have
static_assert(std::is_same<Map3, map<
  pair<int, int>,
  pair<double, int>,
  pair<bool, int>>>::value, "");
1个回答

3
您可能需要手动删除重复项:使用完整的C++14工具 在Coliru上实时演示
auto r = 
    as_map(
        fold(
            fold(m1, m2, [](auto accum, auto elem) { return erase_key<typename decltype(elem)::first_type>(accum); }),
            m1, 
            [](auto accum, auto elem) { return insert(accum, boost::fusion::end(accum), elem); }
        )); 

这很有趣。如果您使用函数对象而不是lambda表达式,您最终会得到类似于以下代码:

auto r = 
    as_map(
        fold(
            fold(m1, m2, erase_corresponding()), 
            m1, 
            insert_helper()
        ));

一个简单的实现 在Coliru上实时运行 仍然依赖于c++1y的初步支持:

 struct erase_corresponding {
    template<typename T, typename U> 
        auto operator()(T map, U elem) const {
            return boost::fusion::erase_key<typename U::first_type>(map);
        }
};

struct insert_helper {
    template<typename T, typename U> 
        auto operator()(T map, U elem) const {
            return boost::fusion::insert(map, boost::fusion::end(map), elem);
        }
};

然而,为了使其完全符合c++03标准,您需要使用RESULT_OF显式地表达出来(这部分我留给读者自行练习)。

刚刚意识到第二个折叠可以简化为一个简单的连接操作 :) - sehe

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接