Search code examples
linuxc++11boostboost-multi-index

boost::multiindex and inheritance


I am trying to inherit from boot::multiindex and see what all I can do, while doing so insert works fine but replace is not.

Code

#include <boost/multi_index_container.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/hashed_index.hpp>
#include <boost/multi_index/identity.hpp>
#include <boost/multi_index/mem_fun.hpp>
#include <string>
#include <utility>
#include <iostream>

using namespace boost::multi_index;

struct employee
{
  std::string name_;
  int id;
  int state;

  employee(std::string name, int id) 
      : name_{std::move(name)},
            id(id),
        state(0) {}


  employee(const employee& copy):
      name_(copy.name_),
      id(copy.id),
      state(copy.state){}
       
  bool operator<(const employee &a) const 
  { 
      return id < a.id; 
  }

  const std::string& get_name() const 
  { 
      return name_; 
  }

};

struct names{};

typedef multi_index_container<
  employee,
  indexed_by<
    ordered_unique<
      identity<employee>
    >,
    hashed_unique<
      tag<names>,
        const_mem_fun<
        employee, const std::string&, &employee::get_name
      >
    >
  >
> employee_container;


typedef employee_container::index<names>::type::iterator employee_iterator_by_name;
//using employee_by_name = employee_container::nth_index<ANTENNA_INDEX_BY_NAME>::type&;

class employee_db: public employee_container
{
    public:
      void add_db(const employee& e)
      {
         this->insert(e);
      }  
      void update_db(
             employee_iterator_by_name& it
                )
      {
         this->replace(it, *it);
      }  


};  

compiling it in Linux

gcc version 8.3.1 20191121 (Red Hat 8.3.1-5) (GCC) 

[sandbox@localhost multiindex]$ rpm -qa | grep boost | grep devel
boost-devel-1.66.0-7.el8.x86_64

[sandbox@localhost multiindex]$ g++  2.cc -c -std=c++11

2.cc: In member function ‘void employee_db::update_db(employee_iterator_by_name&)’:
2.cc:75:31: error: no matching function for call to ‘employee_db::replace(employee_iterator_by_name&, const value_type&)’
          this->replace(it, *it);

What is it that I am doing wrong?


Solution

  • In update_db you're using an employee_iterator_by_name, which is an iterator to index #1, on the index #0 version (the default index) of replace. You want to use index #1 replace:

      void update_db(employee_iterator_by_name& it)
      {
         this->get<names>().replace(it, *it);
      }  
    

    I understand this is just some exploratory code, because calling replace this way does not change anything (you're replacing the value pointed to by it with, well, the value pointed to by it).