【问题标题】:boost::multiindex and inheritanceboost::multiindex 和继承
【发布时间】:2021-02-18 21:20:51
【问题描述】:

我正在尝试从 boot::multiindex 继承,看看我能做什么,虽然这样做插入工作正常,但替换不是。

代码

#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);
      }  


};  

在 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);

我做错了什么?

【问题讨论】:

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


    【解决方案1】:

    在update_db 中,您在replace 的索引#0 版本(默认索引)上使用employee_iterator_by_name,它是索引#1 的迭代器。你想使用索引#1 replace:

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

    我知道这只是一些探索性代码,因为以这种方式调用 replace 不会改变任何内容(您将 it 指向的值替换为 it 指向的值)。

    【讨论】:

    • 是的,它只是插图代码。实际的要大得多。实际上在实际代码中,我将根据名称获取并替换它。感谢您指出错误。
    猜你喜欢
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    • 2011-06-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多