title: Well defined narrowing cast
body: <p>I'm trying to come up with a narrowing cast (a general solution) that gracefully ignores lost data. In Visual Studio, a narrowing cast that loses data triggers a "Run-Time Check Failure #1". I do not want to turn it off, instead I'm trying to implement a <code>narrow_cast</code> that would gracefully do narrowing casts and wouldn't trigger the run time check. </p>
  
  <p>Visual Studio suggests:</p>
  
  <pre><code>char c = (i &amp; 0xFF);
  </code></pre>
  
  <p>So I started with this, and came up with this ugly solution:</p>
  
  <pre><code>template&lt; typename T &gt;
  struct narrow_mask
  {
    static const T value = T(0xFFFFFFFFFFFFFFFF);
  };
  
  template &lt;typename T, typename U&gt;
  T narrow_cast(const U&amp; a)
  {
    return static_cast&lt;T&gt;(a &amp; narrow_mask&lt;T&gt;::value );
  }
  </code></pre>
  
  <p>While it works (VS it seems is perfectly fine with losing data on constants), it's neither complete (no support for non integral data), nor correct (I think it would not work correctly for signed values).</p>
  
  <p>Any suggestions for a better solution, or a better narrow_mask implementation?</p>
  
  <p><strong>Edit:</strong> In face of comments that this question is VS specific, I checked the standard document, and it seems that the result of a narrowing <code>static_cast</code> is implementation dependant. Hence, the question can be nicer stated as creating a well-defined (ergo, not implementation dependant) narrowing cast. I do not care much about the specifics of the result value, as long as it's well defined and dependant on the type (not <code>return 0</code>).</p>