title: C++: Cast operator overloading and references
body: <p>C++ allows for overloading type casts by creating an <code>operator T()</code> where <code>T</code> is the type we want to cast to.</p>
  
  <p>Now, how does this feature play together with references? For example:</p>
  
  <pre><code>struct Y{ int i; };
  
  struct X{
      Y y;
  
      operator Y() const { return y; }
  };
  </code></pre>
  
  <p>Here, we can cast an <code>X</code> to <code>Y</code> which will simply return the contained <code>Y</code>. But what if we want to make a cast to an <code>Y</code> reference. For example, C++ allows us to do this:</p>
  
  <pre><code>struct X{
      Y y;
  
      operator Y&amp;(){ return y; }
      operator const Y&amp;() const { return y; }
  };
  </code></pre>
  
  <p>Now, we can cast an <code>X</code> to a <code>Y</code> reference or a <code>const</code> reference (which also works for a <code>const X</code>). </p>
  
  <p><strong>Is there any difference in the semantics of the first and the second example? What is the best way if I want to allow casting to a reference?</strong></p>
  
  <p>I could imagine that even if I write <code>operator T()</code> without any <code>&amp;</code>, C++ might allow that the cast returns a result by reference (i.e., it might somehow add implicit <code>operator T&amp;()</code> methods when I specify <code>operator T()</code>).</p>
  
  <p>For example, I want the following code to work:</p>
  
  <pre><code>int main(){
      X x;
      Y&amp; y = x; // y now references the y inside x
      y.i = 5;
      std::cout &lt;&lt; x.y.i &lt;&lt; std::endl; // Should print 5 now
  }
  </code></pre>
  
  <p>What is the most simple way to achieve this?</p>