Re: Dumbed-down
Steve Clamage wrote:
Keith Thompson wrote:
fgothamNO@SPAM.com (Frederick Gotham) writes:
unsigned long long const gdp = 12485725486486764U;
...
unsigned long long const population = 297279178249U;
...
unsigned gdp_per_capita = (unsigned)(gdp / population);
But the cast, as many have noted, is generally not a good idea. In the
original example, you might later decide that gdp_per_capita ought to b=
e
a larger type. When (as in real code) the various declarations are
spread far apart, you might not realize that the cast no longer matches
the target type. You could wind up with an explicit narrowing conversio=
n
that changes the value, but without the possibility of a compiler warni=
ng.
A safer option is to use boost::numeric_cast, which checks whether
the value can be preserved in the target type and throws an exception
otherwise.
In fact, I would also like a version in which a similar checking is done
only in debug builds, =E0 la boost::polymorphic_downcast: i.e.
template <class Target, class Source>
inline Target numeric_cast(Source x)
{
assert( x is in the range of Target );
return static_cast<Target>(x);
}
(I'm not sure how to express in C++ what I wrote inside assert( );
when I look into the implementation of boost::numeric::converter,
it seems too complicated for me to understand in a short time.)
--
Seungbeom Kim
---
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.comeaucomputing.com/csc/faq.html ]