How can I improve this design that forces me to declare a member function const and declare variables mutable?

前端 未结 3 1141
情深已故
情深已故 2020-12-20 20:26

For some reason I am iterating over elements of a class in an std::set and would like to slightly modify the keys, knowing that the order will be unchanged.

3条回答
  •  半阙折子戏
    2020-12-20 20:42

    Another option is to const_cast to a reference type :

    class Foo
    {
    public:
        void incrementB() const { ++ const_cast< int& >( b_ ); }
    private:
        int b_;
    };
    

    But as sehe already said, you shouldn't modify set's elements.

提交回复
热议问题