作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
考虑以下片段:
#include <map>
class C {
public:
C() {}
const int& f(const int& x) const
{
// Error: cannot cast const int* to int* const
return myMap.find(&x)->second;
// With a const_cast works:
//return myMap.find(const_cast<int* const>(&x))->second;
}
std::map<int*, int> myMap;
};
int _tmain(int argc, _TCHAR* argv[])
{
int x = 0;
C c;
c.f(x);
return 0;
}
f()
中的错误是由 map 的 find()
的 const 重载采用 const KeyType&
引起的。因为 map 的键类型是int*
,所以这变成了int* const
。 f()
接受一个 const int&
参数,这是正确的,因为该参数永远不会被修改。
不幸的是,这最终导致尝试将 const int*
转换为 int* const
,这会丢失 int 上的 const 限定符并且无法编译。
这有点令人恼火,因为参数肯定从未被修改过 - 它只是用于 find() - 但我仍然需要 const_cast
它。
有没有办法不用 const_cast
来写 f()
?
最佳答案
您可以只更改 map
的类型至 std::map<const int*, int>
;不过,我质疑您是否首先需要指针作为键。正如詹姆斯指出的那样,关键类型应该是 const int*
因为您从不打算通过 map
修改引用对象.如果你这样做,我会更担心。
关于c++ - 被 const 逼入绝境:std::map::find() const 重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5845212/
我是一名优秀的程序员,十分优秀!