如何合并两个 mpl 映射生成新映射



但是我每周使用以下代码,似乎缺少一点。它不会编译。我有两张地图 int -> int。我想生成第三个 int -> int 映射,其中包含来自两个原始文件的所有键值对。(VS2013)任何人?

#include <boost/mpl/map.hpp>
#include <boost/mpl/pair.hpp>
#include <boost/mpl/int.hpp>
#include <boost/mpl/at.hpp>
#include <boost/mpl/copy.hpp>
#include <boost/mpl/assert.hpp>
#include <boost/mpl/has_key.hpp>
typedef boost::mpl::map <
    boost::mpl::pair < boost::mpl::int_<7>, boost::mpl::int_<59>  >
>::type Original1;
typedef boost::mpl::map <
    boost::mpl::pair < boost::mpl::int_<11>, boost::mpl::int_<61>  >
>::type Original2;
typedef boost::mpl::copy <
    Original1,
    boost::mpl::back_inserter < Original2 >
>::type Merged;
BOOST_MPL_ASSERT((boost::mpl::has_key<Merged, 7>));
int _tmain(int argc, _TCHAR* argv[])
{
    const int i = boost::mpl::at<Merged, boost::mpl::int_<7> >::type::value;
    return 0;
}

你的代码有两个问题。简单的一个在这里:

BOOST_MPL_ASSERT((boost::mpl::has_key<Merged, 7>));

键是类型,7不是类型。您要检查密钥mpl::int_<7>

第二个在这里:

typedef boost::mpl::copy <
    Original1,
    boost::mpl::back_inserter < Original2 > // <==
>::type Merged;

mpl::back_inserter是元编程等价于std::back_inserter,它创建了一个通过push_back()输出的输出迭代器。同样,back_inserter需要一个"反向可扩展序列",因为它使用mpl::push_backmpl::map不是向后可扩展序列。如果你看它的参考资料,没有push_back,只有insert。所以你需要这样做:

using Merged =
    mpl::copy<
        Original1,
        mpl::inserter<Original2, mpl::insert<mpl::_1, mpl::_2>> // <==
    >::type;
<小时 />

我不太明白mpl::quote在做什么,但它似乎坏了(呃,实际上,mpl::insert需要 3 个参数,mpl::quote3不允许默认最后一个参数)。如果你写:

template <template <class... > class F>
struct quote {
    template <class... Args>
    struct apply {
        using type = typename F<Args...>::type;
    };
};

然后你可以写:

mpl::inserter<Original2, quote<mpl::insert>>