如何为成员创建boost multi_index密钥?

时间:2015-12-21 16:01:39

标签: c++ boost-multi-index

我们说我有以下内容:

struct foo {
   int i;
};

struct bar {
    foo f;
};

有没有办法为容器创建一个密钥f.i(包装到函数除外),持有struct bar

直截了当的方式似乎不起作用:

namespace mpi = boost::multi_index;
typedef mpi::multi_index_container<bar,
     mpi::indexed_by< mpi::hashed_unique<bar,
         mpi::member< bar, int, &bar::fo.i>>
> > Foobar;

2 个答案:

答案 0 :(得分:3)

多索引的member索引助手仅用于访问值类的直接成员,并且不能以嵌套方式组合。

而是使用预期的机制并编写自己的密钥提取器。它将使代码维护变得更容易,而不是试图利用基本的内置功能来实现它从未实现过的功能。

struct foo_i_from_bar
{
    typedef int result_type;
    result_type operator()(const bar& b) const { return b.f.i; }
};

typedef boost::multi_index::multi_index_container<bar,
     boost::multi_index::indexed_by< boost::multi_index::hashed_unique<foo_i_from_bar>
         > > Foobar;

答案 1 :(得分:1)

它很难看,但它有效。

#include <boost/multi_index_container.hpp>
#include <boost/multi_index/hashed_index.hpp>
#include <boost/multi_index/member.hpp>

struct foo {
    int i;
};

struct bar {
    typedef int result_type;
    foo f;
};

namespace mpi = boost::multi_index;

typedef mpi::member< bar, int, (int bar::*)( offsetof(bar,f.i) )> bar_member;
                                         //  ^^^^^^^^ bar::f.i      

typedef mpi::multi_index_container< bar, mpi::indexed_by< mpi::hashed_unique<bar, bar_member > > > Foobar;

Foobar foobar;

......这也有效......

typedef mpi::member< bar, int, (int bar::*)( (size_t)&(((bar*)0)->f.i) )> bar_member;
相关问题