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

后端 未结 19 1964
天涯浪人
天涯浪人 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:01

    For a detailed explanation, please see the heading "Avoid Duplication in const and Non-const Member Function," on p. 23, in Item 3 "Use const whenever possible," in Effective C++, 3d ed by Scott Meyers, ISBN-13: 9780321334879.

    alt text

    Here's Meyers' solution (simplified):

    struct C {
      const char & get() const {
        return c;
      }
      char & get() {
        return const_cast(static_cast(*this).get());
      }
      char c;
    };
    

    The two casts and function call may be ugly but it's correct. Meyers has a thorough explanation why.

提交回复
热议问题