[英]Can I cast a map with a non-const value type to one with a const value type?
I have something like the following: 我有类似以下内容:
map<int, StructType> map;
const map<int, StructType>& GetMap() { return map; }
I'd like to do something along these lines: 我想按照以下方式做些事情:
const map<int, const StructType>& GetConstMap() { return map; }
Is there any way I can add this const
-ness to the value type of the map? 有什么办法可以将此
const
-ness添加到地图的值类型?
The interface of std::map
is designed so that const map<K,T>
effectively has a const value type, by never exposing non-const access to its elements. 设计
std::map
的接口是为了使const map<K,T>
有效地具有const值类型,方法是从不公开对其元素的非const访问。
So you cannot add, remove or modify elements through a const map
reference. 因此,您不能通过
const map
引用添加,删除或修改元素。
So: 所以:
struct X
{
map<int, StructType> m;
const map<int, StructType>& GetConstMap() const { return m; }
}
Is what you want. 是你想要的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.