map with const keys but non const values?

后端 未结 5 613
半阙折子戏
半阙折子戏 2021-01-12 18:00

I have a situation, where I would like to have a map that does not allow to add/remove keys after initialization, but the values are allowed to change (thus I cannot simply

5条回答
  •  北荒
    北荒 (楼主)
    2021-01-12 19:03

    I see 2 options here

    1. Make the map const and use const_cast when changing something

      const std::map myMap;

      myMap[1] = 2; // NOT OK, because const map

      (const_cast&>(myMap)).at(1) = 2; // OK with const_cast

    2. make an wrapper class or derive an custom map that has only read and update existing value methods

    I don't think there is an built in way to make an map only with update value, and restrict and insert.

提交回复
热议问题