map with const keys but non const values?

后端 未结 5 610
半阙折子戏
半阙折子戏 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 18:48

    Could you create a wrapper that contains the value that allows the value to be mutated when const and put that in the map instead? Something like:

    template
    class Mutable {
        mutable T value;
    public:
      const Mutable& operator=(const T& v) const { value = v; return *this; }
      T& get() const { return value; }  
    };
    

    Then your map can be of type

    const std::map>
    

    Live demo.

提交回复
热议问题