static_cast with bounded types
<p>When you cast an int in short with a classic static_cast (or c cast), if the value is out of the short limits, the compiler will truncat the int.</p>

<p>For example:</p>

<pre><code>int i = 70000;
short s = static_cast&lt;short&gt;(i);
std::cout &lt;&lt; "s=" &lt;&lt; s &lt;&lt; std::endl;
</code></pre>

<p>Will display:</p>

<pre><code>s=4464
</code></pre>

<p>I need a "inteligent" cast able to use the type limit and, in this case return 32767. Something like that:</p>

<pre><code>template&lt;class To, class From&gt;
To bounded_cast(From value)
{
  if( value &gt; std::numeric_limits&lt;To&gt;::max() )
  {
    return std::numeric_limits&lt;To&gt;::max();
  }
  if( value &lt; std::numeric_limits&lt;To&gt;::min() )
  {
    return std::numeric_limits&lt;To&gt;::min();
  }
  return static_cast&lt;To&gt;(value);
}
</code></pre>

<p>This function works well with int, short and char, but need some improvments to works with double and float.</p>

<p>But is it not a reinvention of the wheel ?</p>

<p>Do you know an existing library to do that ?</p>

<p><em><strong>Edit:</em></strong></p>

<p>Thanks. The best solution I found is this one:</p>

<pre><code>template&lt;class To, class From&gt;
To bounded_cast(From value)
{
  try
  {
    return boost::numeric::converter&lt;To, From&gt;::convert(value);
  }
  catch ( const boost::numeric::positive_overflow &amp; )
  {
    return std::numeric_limits&lt;To&gt;::max();
  }
  catch ( const boost::numeric::negative_overflow &amp; )
  {
    return std::numeric_limits&lt;To&gt;::min();
  }
}
</code></pre>
