legalize+ (Richard)
2014-06-18 05:48:44 UTC
[Please do not mail me a copy of your followup]
I was trying to write something that would throw an assert when I did
a narrowing cast that truncated, so I wrote something like:
template <typename T, typename U>
T safe_narrowing_cast(const U value)
{
T const max_value = std::numeric_limits<T>::max();
U const max_u_value = static_cast<U>(max_value);
assert(value < max_u_value);
return static_cast<T>(value);
}
However, what surprised me is that when U was long long and T was
double, i.e. casting a long long to a double, that I got the
following:
max_value 1.7976931348623157e+308 const double
max_u_value -9223372036854775808 const __int64
I expected static_cast<double> to truncate, not act like
reinterpret_cast and just jam the bits in there.
My intention in the assert is to say "does the given value fit inside
the range of the target". In my specific case, value is something
like 70 or 200, so it clearly fits in the range of a double, but
obviously my assert isn't specified properly.
What am I missing?
I was trying to write something that would throw an assert when I did
a narrowing cast that truncated, so I wrote something like:
template <typename T, typename U>
T safe_narrowing_cast(const U value)
{
T const max_value = std::numeric_limits<T>::max();
U const max_u_value = static_cast<U>(max_value);
assert(value < max_u_value);
return static_cast<T>(value);
}
However, what surprised me is that when U was long long and T was
double, i.e. casting a long long to a double, that I got the
following:
max_value 1.7976931348623157e+308 const double
max_u_value -9223372036854775808 const __int64
I expected static_cast<double> to truncate, not act like
reinterpret_cast and just jam the bits in there.
My intention in the assert is to say "does the given value fit inside
the range of the target". In my specific case, value is something
like 70 or 200, so it clearly fits in the range of a double, but
obviously my assert isn't specified properly.
What am I missing?
--
"The Direct3D Graphics Pipeline" free book <http://tinyurl.com/d3d-pipeline>
The Computer Graphics Museum <http://computergraphicsmuseum.org>
The Terminals Wiki <http://terminals.classiccmp.org>
Legalize Adulthood! (my blog) <http://legalizeadulthood.wordpress.com>
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]
"The Direct3D Graphics Pipeline" free book <http://tinyurl.com/d3d-pipeline>
The Computer Graphics Museum <http://computergraphicsmuseum.org>
The Terminals Wiki <http://terminals.classiccmp.org>
Legalize Adulthood! (my blog) <http://legalizeadulthood.wordpress.com>
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]