2

我有一个融合集,想将其转换为融合图。

#include <cstdlib>
#include <iostream>

#include <boost/fusion/include/fold.hpp>
#include <boost/fusion/include/map.hpp>
#include <boost/fusion/include/make_map.hpp>
#include <boost/fusion/include/push_back.hpp>
#include <boost/fusion/include/pair.hpp>
#include <boost/fusion/container/set.hpp>
#include <boost/fusion/include/for_each.hpp>
#include <boost/fusion/include/at_key.hpp>

struct node_base
{
    int get() {return 123;}
};
struct node_a : public node_base
{
node_a(){std::cout << "node_a::Ctor"<< std::endl;}
};
struct node_b : public node_base
{
node_b(){std::cout << "node_b::Ctor"<< std::endl;}
};
struct node_c : public node_base
{
node_c(){std::cout << "node_c::Ctor"<< std::endl;}
};

typedef ::boost::fusion::set<node_a,node_b,node_c> my_fusion_set;
my_fusion_set my_set;

struct push_back_map
{
    typedef ::boost::fusion::map<> result_type;

    template<class NODE>
    ::boost::fusion::map<> operator() (const ::boost::fusion::map<> & m, const NODE & n)
    {
    return ::boost::fusion::push_back(
        m
        , ::boost::fusion::make_pair<NODE>(n)
        );
    }
};

::boost::fusion::map<> my_map =
::boost::fusion::fold(
    my_set
    , ::boost::fusion::map<>()
    , push_back_map()
    );

struct print_map
{
    template<class P>
    void operator()(P & p) const
    {
    std::cout << p.second.get() << std::endl;
    }
};

int main()
{
    ::boost::fusion::for_each(my_map, print_map());
    std::cout << ::boost::fusion::at_key<node_a>(my_set).get() << std::endl;
    //std::cout << ::boost::fusion::at_key<node_a>(my_map).second.get() << std::endl;
    system("pause");
    return 0;
}

此代码编译。但它无法打印出 my_map 的结果。my_set 构造成功。my_map 简单地从 my_set 转换,每个元素的原始类型作为键,默认构造函数的实例对象作为值。我想知道 my_map 是否从 fusion::fold 成功创建。my_set 可以通过调用 fusion::at_key<> 进行查询,但 my_map 不适用于 at_key<>。谢谢!

4

1 回答 1

3

我想不出一种简洁的方式来fusion::map创建 fusion::setwith fold。所以这个答案不会直接解决你的问题。我发布这个以防万一这会给你一些提示。
如何准备一个类型列表(my_types如下所示),并从该列表创建和而不是fusion::set直接创建? 例如:fusion::mapfusion::mapfusion::set

namespace bf = boost::fusion;
namespace bm = boost::mpl;

typedef bm::vector<node_a,node_b,node_c> my_types;
typedef bm::fold<
          my_types
        , bm::vector<>
        , bm::push_back< bm::_1, bf::pair< bm::_2, bm::_2 > >
        >::type my_map_types;

int main() {
    bf::result_of::as_set<my_types>::type my_set;
    bf::result_of::as_map<my_map_types>::type my_map;
    std::cout << bf::at_key<node_a>(my_set).get() << std::endl;
    std::cout << bf::at_key<node_a>(my_map).get() << std::endl;
}

这是对ideone的测试。顺便说一句,如果你的 key-type 和 value-typefusion::map总是相同的,fusion::set就会达到这个目的。

于 2011-07-16T22:10:53.607 回答