title: How do I remove code duplication between similar const and non-const member functions?
body: <p>Let's say I have the following <code>class X</code> where I want to return access to an internal member:</p>
  
  <pre><code>class Z
  {
      // details
  };
  
  class X
  {
      std::vector&lt;Z&gt; vecZ;
  
  public:
      Z&amp; Z(size_t index)
      {
          // massive amounts of code for validating index
  
          Z&amp; ret = vecZ[index];
  
          // even more code for determining that the Z instance
          // at index is *exactly* the right sort of Z (a process
          // which involves calculating leap years in which
          // religious holidays fall on Tuesdays for
          // the next thousand years or so)
  
          return ret;
      }
      const Z&amp; Z(size_t index) const
      {
          // identical to non-const X::Z(), except printed in
          // a lighter shade of gray since
          // we're running low on toner by this point
      }
  };
  </code></pre>
  
  <p>The two member functions <code>X::Z()</code> and <code>X::Z() const</code> have identical code inside the braces.  This is duplicate code <strong>and can cause maintenance problems for long functions with complex logic</strong>.  </p>
  
  <p>Is there a way to avoid this code duplication?</p>