给出带有非恒定指针键的std :: map,如何通过恒定指针访问它?

问题描述 投票:0回答:1

[类型为std::map<A*, B*> m的映射描述了类型A的对象和类型B的对象之间的对应关系。有一个函数int exctractInfo(const A *a)需要从类型为B的给定对象对应的类型为A的对象中读取一些信息。这是一个语义上恒定的操作,不需要更改任何内容,我们只需要读取一些信息,但是问题是C ++ 不允许通过常量指针访问map m

请考虑以下代码:

#include <map>

class A {

};

class B {
    int info_;

public:
    int info() const { return info_; }
};

std::map<A*, B*> m;

int exctractInfo(const A *a) {
    auto it = m.find(a);
    if (it != m.end() && it->second) {
       return it->second->info();
    }
    return -1;
}

int main () {
    return 0;
}

Here's a link用于此代码的在线编译器。我收到以下错误:

错误:从'const A *'到'std :: map :: key_type {aka A *}'的无效转换” [-fpermissive]

现在我看到两个解决方案:

  1. 将类型std::map<A*, B*>重写为std::map<const A*, B*>,因为我可以访问源代码,但这基本上是库对象的一种,并且很多代码都依赖于它,因此必须更改,因此更改地图类型确实是不可取的;

  2. 使用const cast像这样:auto it = m.find(const_cast<A*>(a));,这似乎也不是一个好的解决方案,更多的是hack。

我不明白为什么它不起作用。例如,如果键是std::stringint,我就可以通过std::map<std::string, B*>来访问const std::string。那么我的例子怎么了?有没有适当的方法来处理这种情况?

c++ stl const std stdmap
1个回答
0
投票

我不明白为什么它不起作用。例如,如果键是std :: string或int,我就可以通过const std :: string访问std :: map了。那我的例子怎么了?

© www.soinside.com 2019 - 2024. All rights reserved.