【问题标题】:can't use a const argument to find() method of the boost::multi_index_container不能对 boost::multi_index_container 的 find() 方法使用 const 参数
【发布时间】:2013-09-16 05:56:34
【问题描述】:

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

基类:

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 没有说明原因!

标签: c++ boost-multi-index


【解决方案1】:

将索引 1 定义为

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

【讨论】:

  • 哦,终于有人来帮忙了。我会检查并回复你。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-02
  • 2013-12-06
  • 2016-02-05
  • 1970-01-01
相关资源
最近更新 更多