不能使用 const 参数来查找 boost::multi_index_container 的 () 方法

can't use a const argument to find() method of the boost::multi_index_container

本文关键字:container index 方法 multi 参数 const 查找 不能 boost      更新时间:2023-10-16

我有一个非常简单的多索引容器,它索引类的成员如下:

基类:

class AgentInfo {
public:
    Agent * agent;
    bool valid;
    AgentInfo(Agent * a_, bool valid = true);
    AgentInfo();
};

//helper tags used in multi_index_container
struct agent_tag{};
struct agent_valid{};

声明multi_index_container的类:

class AgentsList {
public:
private:
//main definition of the container
typedef boost::multi_index_container<
        AgentInfo, indexed_by<
        random_access<>//0
,hashed_unique<tag<agent_tag>,member<AgentInfo, Agent *, &AgentInfo::agent> >//1
,hashed_non_unique<tag<agent_valid>,member<AgentInfo, bool, &AgentInfo::valid> >//2
        >
        > ContainerType;
//the main storage
ContainerType data;
//easy reading only
typedef typename nth_index<ContainerType, 1>::type Agents;
public:
    //  given an agent's reference, returns a const version of a single element from the container.
    const AgentInfo  &getAgentInfo(const Agent * agent, bool &success)const {
        success = false;
        AgentsList::Agents &agents = data.get<agent_tag>();
        AgentsList::Agents::iterator it;
        if((it = agents.find(agent)) != agents.end())//<-- error in .find()
        {
            success = true;
        }
        return  *it;
    }
};

我的问题在于getAgentInfo()这是一种访问器方法。错误很明显:

error: invalid conversion from ‘const Agent*’ to ‘Agent*’
  • 我无法输入非常量Agent*因为我是从代码库的其他部分获取的。

  • 我不喜欢使用const_cast

有没有办法使用常量代理调用.find()方法?谢谢

将索引 1 定义为

hashed_unique<
  tag<agent_tag>,
  member<AgentInfo, Agent *, &AgentInfo::agent>,
  boost::hash<const Agent*>, std::equal_to<const Agent*>
>