我有一个定义如下map
:
typedef std::map<AsnIdentifier, AsnValue, AsnComparator> MibMap;
我有一个这样的映射,我想将其传递给另一个函数,以便传递到的函数无法修改它。
void someFunc() {
MibMap someMap = GetMibMap();
otherFunc(someMap);
}
对于不变性,otherFunc
的签名可能如下所示:
void otherFunc(const MibMap& someMap);
但是一旦使用地图的功能find
我就会得到一个非常详细的编译错误。
void otherFunc(const MibMap& someMap) {
MibMap::iterator findVal = someMap.find(//pass the key to find); //this does not compile
}
一旦我从方法签名中删除const
,编译错误就会消失。这是什么原因呢?我想保持地图不可修改,但同时我不确定这个编译错误。
编辑:编译错误如下:
no suitable user-defined conversion from "std::_Tree_const_iterator... (and a whole long list)
如果您查看适合std::map::find
的参考文档,您将看到它有两个重载,它们在 1. 隐式this
参数的常量限定,以及 2. 返回类型:
iterator find( const Key& key );
const_iterator find( const Key& key ) const;
从这里开始,您的问题应该很明显:您正在调用const
限定find
,但您正在尝试将其结果转换为MibMap::iterator
。将findVal
类型更改为const_iterator
(或仅使用auto
(,它将起作用。