简体   繁体   English

我可以将具有非常量值类型的映射转换为具有常量值类型的映射吗?

[英]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.

相关问题 对类型“const int *”的非 const 左值引用不能绑定到不相关类型“int *”的值 - non-const lvalue reference to type 'const int *' cannot bind to a value of unrelated type 'int * 我可以为非const参考参数赋值吗? - Can I assign a value to a non-const reference parameter? const object 可以修改无主非常量 object 的值吗? - Can a const object modify a value of unowned non-const object? 是否可以使用非const键类型的unordered_map? - Is it possible to have an unordered_map with non-const key type? 类型&#39;_wrap_iter的非常量左值引用 <pointer> &#39;无法绑定到无关类型的值 - Non-const lvalue reference to type '_wrap_iter<pointer>' cannot bind to a value of unrelated type 如何处理对类型&#39;A&#39;的非const左值引用不能绑定到该指针的不相关类型&#39;B&#39;的值? - How to handle non-const lvalue reference to type 'A' cannot bind to a value of unrelated type 'B' for this pointer? 如何使用const值初始化const对象的非const属性? - How to initialize a non-const attribute of a const object with a const value? 从由 const 模板参数参数化的类型转换为非常量模板参数 - Cast from type parametrized by const template argument to non-const template argument Const数据类型不能分配到非const数据类型 - Const data type cannot be assigned into a non-const data type 右值类型的非常量引用 - non-const reference of type from an rvalue
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM