2

I have a struct

struct employee
{
  int         id;
  std::string name;

  employee(int id,const std::string& name):id(id),name(name){}

  bool operator<(const employee& e)const{return id<e.id;}

  getId(){return id;}
  getName(){return name;}
};

If I make boost multi index like this from tutorial everything works well

typedef multi_index_container<
  employee,
  indexed_by<
    // sort by employee::operator<
    ordered_unique<identity<employee> >,

    // sort by less<string> on name
    ordered_non_unique<member<employee,std::string,&employee::name> >
  > 
> employee_set;

But if I make members of employee struct private, then I lose ability to use em as keys for container. I tried put pointers to getter functions like this &emploeyy::getName but it did not solver the problem.

So my question is: how to use private members as keys for multi index container?

Demaunt
  • 1,183
  • 2
  • 16
  • 26

1 Answers1

3

There are many key extractors to be used. Find the predefined ones in the docs: http://www.boost.org/doc/libs/1_66_0/libs/multi_index/doc/tutorial/key_extraction.html#predefined_key_extractors

Instead of member<> you can use mem_fun<> or const_mem_fun.

Live On Coliru

#include <string>

class employee {
    int id;
    std::string name;

  public:
    employee(int id, const std::string &name) : id(id), name(name) {}

    bool operator<(const employee &e) const { return id < e.id; }

    int getId() const { return id; }
    std::string getName() const { return name; }
};

#include <boost/multi_index/mem_fun.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index_container.hpp>

namespace bmi = boost::multi_index;
typedef bmi::multi_index_container<
    employee,
    bmi::indexed_by<
        bmi::ordered_unique<bmi::identity<employee> >,
        bmi::ordered_non_unique<bmi::const_mem_fun<employee, std::string, &employee::getName> >
    > > employee_set;

int main() {}
sehe
  • 374,641
  • 47
  • 450
  • 633