可以将非const值类型的映射强制转换为const值类型的映射吗?

Can I cast a map with a non-const value type to one with a const value type?

本文关键字:类型 映射 const 转换      更新时间:2023-10-16

我有如下内容:

map<int, StructType> map;
const map<int, StructType>& GetMap() { return map; }

我想这样做:

const map<int, const StructType>& GetConstMap() { return map; }

我是否可以将这个const -ness添加到映射的值类型中?

std::map的接口设计使const map<K,T>有效地具有const值类型,通过从不暴露对其元素的非const访问。

因此不能通过const map引用添加、删除或修改元素。

:

struct X
{
    map<int, StructType> m;
    const map<int, StructType>& GetConstMap() const { return m; }
}

就是你想要的