【问题标题】:Searching a boost::bimap for the current class instance在 boost::bimap 中搜索当前类实例
【发布时间】:2015-10-18 07:03:08
【问题描述】:

好的,所以我声明了一个 boost::bimap:

boost::bimap<object*, position> object_list;

object 和 position 分别是一个类和一个结构体。

在bimap中存储的当前对象内,我想找到它自己的入口。

我目前正在尝试这样做:

void order::do_thing() {
    ...
    position pos = object_list.left.at(this);
    ...
}

我在解析错误输出时遇到了麻烦,但似乎 bimap 的 at 函数不喜欢它的 const-ness 和/或 reference-ness(是的,我知道这是一个右值)。

进行此搜索的正确/建议方法是什么?

这是错误的sn-p:

order.cpp:117:56:   required from here
/usr/include/boost/bimap/container_adaptor/associative_container_adaptor.hpp:207:56: error: no match for call to ‘(const boost::bimaps::container_adaptor::detail::key_to_base_identity<object*, object* const>) (order* const&)’
                 this->template functor<key_to_base>()(k)

(添加编辑以解决 sehe 的 cmets 并指出问题)

抱歉,如果我的帖子不符合礼仪,我是在 SO 上发帖的新手,并且我假设只是转储了我的所有代码(只是为了包含这部分代码的自定义对象和模板)是数百个行)会被认为是错误的形式,所以我将其缩减到(我认为是)仍然能解决问题的最低限度。

为了解决测试用例链接,我确实编写了测试用例。在这种情况下,我将向量换成 bimap 以添加位置代码,这实际上无法编译(尽管我会说我不是很明确地指出它是编译错误,而不是堆栈跟踪)。我假设您(sehe)以为我在谈论运行时错误,否则我看不出链接的相关性。

无论如何,我正在将代码缩减到实际的最小值以重现错误,因此我可以将其发布在这里,然后才意识到实际问题。如上所示,bimap 保存值 &lt;object*, position&gt; 但试图将自身插入 bimap 的类是 order 类:void订购::do_thing() {

所以结果是一个简单的类型错误。对不起,大家,问了一个非常愚蠢的问题。我想这就是我凌晨 3 点做项目的收获。

【问题讨论】:

标签: c++ boost bimap


【解决方案1】:

没有问题。

我能想到的唯一陷阱是你有this 隐式常量。在这种情况下,地图将不得不采用指向 const object 的指针!

在此处查看此示例。取消注释 // const 以查看 const 的变化:

Live On Coliru(非常量)

Live On Coliru(常量)

#include <boost/bimap.hpp>
#include <iostream>

using position = std::string;

#define USE_CONST // const

struct object {
    template <typename BiMap>
    position get_position(BiMap const& bimap) USE_CONST {
        return bimap.left.at(this);
    }
};

int main() {
    std::vector<object> instances(10);

    boost::bimap<object USE_CONST*, position> mapping;

    for (auto& instance : instances)
        mapping.insert({&instance, "instance #" + std::to_string(mapping.size()+1)});

    for (auto& instance : instances)
        std::cout << "Instance reports " << instance.get_position(mapping) << "\n";
}

打印

Instance reports instance #1
Instance reports instance #2
Instance reports instance #3
Instance reports instance #4
Instance reports instance #5
Instance reports instance #6
Instance reports instance #7
Instance reports instance #8
Instance reports instance #9
Instance reports instance #10

【讨论】:

  • 从技术上讲不是问题,我认为您的链接有点过头了,但是将代码配对以在此处发布让我看到了问题,所以我会给你答案.
猜你喜欢
  • 2012-11-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多