【问题标题】:Add more indicies to existing multi index container向现有的多索引容器添加更多索引
【发布时间】:2014-02-04 02:33:24
【问题描述】:

我目前正在使用 Boost::multi_index_container 并且它工作得很好。但是我想封装代码并创建一个看起来像这样的模板类

template<class T>
class LookUp
{
    boost::multi_index<T, indexed_by<___predefined indices___> > myTable;

    void Foo();
}

这个包装器中基本上使用了预定义的索引,但是对于专门的 T,我还想添加额外的索引。是否可以向myTable 添加其他索引?也许额外的模板参数?但是附加索引的数量是未知的。

【问题讨论】:

  • 查看 MIC 源文件 - 本质上,您必须模仿其配置(模板)参数的一部分,并将它们转发到随附的 MIC。
  • @IgorR。这正是我想做的,但是 boost 文档对我来说有点混乱,我不知道如何实现结果。

标签: c++ boost multi-index boost-multi-index


【解决方案1】:

有一个特点。让我们发明吧:

namespace traits
{
    template <typename T> struct predefined_indexes;
}


template <typename T> using MultiIndex = multi_index_container<T, traits::predefined_indexes<T> >;

现在的想法是我们可以实例化我们的 MIC:

MultiIndex<T> myTable;

让我们尝试一个简单的例子:

//////
// example from http://www.boost.org/doc/libs/1_55_0/libs/multi_index/example/fun_key.cpp
struct name_record
{
    name_record(std::string given_name_,std::string family_name_): given_name(given_name_),family_name(family_name_) {}
    std::string name() const { return family_name + " " + given_name; }
    std::string given_name, family_name;
};

std::string::size_type name_record_length(const name_record& r)
{
    return r.name().size();
}

namespace traits
{
    template <> struct predefined_indexes<name_record> :
        indexed_by<
            ordered_unique<
                BOOST_MULTI_INDEX_CONST_MEM_FUN(name_record,std::string,name)
            >,
            ordered_non_unique<
                global_fun<const name_record&,std::string::size_type,name_record_length>
            >
        >
    {
    };
}

Working Live On Coliru

int main()
{
    using MyTable = MultiIndex<name_record>;
    MyTable myTable;

    myTable.insert(name_record("Joe","Smith"));
    myTable.insert(name_record("Robert","Nightingale"));
    myTable.insert(name_record("Robert","Brown"));
    myTable.insert(name_record("Marc","Tuxedo"));

    /* list the names in myTable in phonebook order */
    std::cout << "Phonenook order\n" << "---------------" << std::endl;
    for(MyTable::iterator it=myTable.begin();it!=myTable.end();++it){
        std::cout << it->name() << std::endl;
    }

    /* list the names in myTable according to their length*/

    std::cout<<"\nLength order\n"
        <<  "------------"<<std::endl;
    for(nth_index<MyTable,1>::type::iterator it1=get<1>(myTable).begin();
            it1!=get<1>(myTable).end();++it1){
        std::cout<<it1->name()<<std::endl;
    }
}

输出

Phonenook order
---------------
Brown Robert
Nightingale Robert
Smith Joe
Tuxedo Marc

Length order
------------
Smith Joe
Tuxedo Marc
Brown Robert
Nightingale Robert

【讨论】:

    猜你喜欢
    • 2018-08-24
    • 1970-01-01
    • 2018-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多