Safe static_cast in C++ in a codebase How would you review this way of implementing a std::static_cast 

template &lt;typename ToType, typename FromType&gt;
ToType safe_static_cast( const FromType &amp;from )
{
    assert( from &lt;= std::numeric_limits&lt;ToType&gt;::max() );
    assert( from &gt;= std::numeric_limits&lt;ToType&gt;::min() );

    return static_cast&lt;ToType&gt;(from);
}


Is assertions on the limits a good way?
This is a very interesting question.

First, I would reconsider the name. safe_static_cast implies that it is more general than it is. The types must have std::numeric_limits specializations in your implementation, so clearly you are thinking of numeric types. Maybe safe_numeric_cast or even numeric_cast would be a better name.

Secondly, assert is too often compiled out, so I would ask to consider alternatives which aren't. One alternative is throwing std::out_of_range. Another alternative is to saturate the destination type: if the source value is larger than the largest destination value, return the largest destination value.

Consider FromType = int, from = -1, ToType = unsigned int. Note that -1 &gt;= 0u is true.

Consider the range of floating point types: min() is the lowest positive floating point value.

Consider floating point infinities: numeric_cast&lt;double, double&gt; should always be fine, right? But the comparison will fail for infinity.

Consider floating point nans: similarly, all comparisons fail for nans.