How do I remove code duplication between similar const and non-const member functions?

后端 未结 19 1992
天涯浪人
天涯浪人 2020-11-22 00:30

Let\'s say I have the following class X where I want to return access to an internal member:

class Z
{
    // details
};

class X
{
    std::vec         


        
19条回答
  •  野性不改
    2020-11-22 01:05

    To add to the solution jwfearn and kevin provided, here's the corresponding solution when the function returns shared_ptr:

    struct C {
      shared_ptr get() const {
        return c;
      }
      shared_ptr get() {
        return const_pointer_cast(static_cast(*this).get());
      }
      shared_ptr c;
    };
    

提交回复
热议问题