C++ int_cast function for checked casts? In order to detect run-time integer casting problems, I've created this function*:

template&lt;typename TTo, typename TFrom&gt;
static inline TTo int_cast(TFrom value)
{
    TTo result = static_cast&lt;TTo&gt;(value);
    if (static_cast&lt;TFrom&gt;(result) != value || (result &gt;= TTo()) != (value &gt;= TFrom()))
    {
        throw std::out_of_range("numeric_cast: value out of range");
    }
    return result;
}


Two questions:


Are there any loopholes in this function I have not accounted for (e.g. undefined behavior)?
What would be the best way to extend this to perform double-to-float and floating-to-integral conversions?


*Note: Yes, I realize Boost has a function like this. But I want my own. :)
Are there any loopholes in this function I have not accounted for (e.g. undefined behavior)?


No. Static cast will not result in undefined behavior.
If it compiles then the cast is good (assuming integer/float types).

Though some of your cast may potentially result in implementation defined behavior (depending on the sign-dness and size of the types).

signed x = int_cast&lt;signed,unsigned&gt;(-1); // implementation defined behavior.


Since this is only supposed to work on int(s). Then I would make it be a compile time error if you tried to use it with other types. You may also be able to do some compile time range checking when the inputs are literals.

In the following:

(result &gt;= TTo()) != (value &gt;= TFrom())


I am assuming this is some form of signdness test (to make sure both source and destination have the same sign). If you are going to do this please comment the code explaining exactly how you think it works.

There are integer traits that allow you to pull the signdess and size of the template type from the input/output types. You could potentially look at this to help identify things.