Boost Multi_Index Question

坚强是说给别人听的谎言 提交于 2019-12-06 03:56:58

From skimming over the boost multi_index library docs I'd say what you want is not possible with this library. Looking at its rationale it appears that it is only made for indexing elements that are fully indexable over all "dimensions". (You might try asking on the boost users mailing list if there are any hacks to allow "sparse" index dimensions.)

Anyways - depending on the exact nature of your problem you might be able to work around it by using a boost::optional as indexing type. (Although I'm not even sure it's possible to index by boost::optional.)

Having assert() in your get_i() and get_j() functions will cause a hard program stop when multi_index asks for the i or j values for indexing.

It sounds like you want Null Object Pattern behaviour. I.e. m_i and m_j are data-types that take special values to indicate they are not set (if they were pointers, the NULL pointer would serve this purpose). Then your multi-index could index on those values, lumping all the null values together.

When accessing the data, you can use boost::range to filter out the null values:

// Predicate for null testing
struct is_not_null {
    bool operator()(const Foo& f) { return f.get_i() != NULL && f.get_j() != NULL; }
};

Foo_set::nth_index<1>::type& idx = foos.get<1>();
BOOST_FOREACH(const Foo& f, idx | filtered(is_not_null())) {
    ;// do something with the non-null Foo's
}

If you don't want to pollute the value-space of your variables (i.e. there is no meaningful null value that can be stored), you could also look into converting your m_i and m_j members into boost::optional's. With a bit more functor wrapping, you could create a composite index of <bool, int>, which would allow you to access set or unset Foo's separately. You can further compose the index to combine i and j with a composite index that looks like <bool, bool, int, int>.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!