|
Boost : |
From: David Abrahams (dave_at_[hidden])
Date: 2003-01-16 08:13:13
Bjorn.Karlsson_at_[hidden] writes:
>> From: Thorsten Ottosen [mailto:nesotto_at_[hidden]]
>> > What would the advantage be over using boost::numeric_cast
>> directly, and
>> > thus explicitly?
>>
>> you would't have to worry about if you forgot a numeric_cast
>> somewhere in
>> your code
>> or if you compiled on a platform with different ranges for
>> built-ins which
>> suddenly
>> could make conversion problems appear.
>
> That you don't have to worry is only true to a small extent - you still need
> to worry, by protecting the code *somwhere* with a try/catch block. This is
> also true for numeric_cast, but then it's straightforward to grok the code
> when reading it. Obviously, the (potential) problems are always there as
> soon as one starts mixing signed/unsigned types, and when assigning to a
> potentially smaller type; they must always be checked regardless.
>
>> that depends on what the "problem" is. I would say that an
>> _undetected_
>> false conversion
>> is the biggest problem.
>
> Agreed!
>
>> >Doing it "manually", and acknowledging the potential problem by
>> > using numeric_cast is (in addition to ensuring correct behavior)
>> > self-documenting, a property that I think is rather important.
>>
>> by using a wrapper, you also acknowledge a potential problem.
>
> Yes, and when writing code like this: safe_numeric<unsigned char> t=u;, a
> reader can understand that - the code has documented itself. But I don't see
> an advantage over writing unsigned char t=numeric_cast<unsigned
> char>(u);
The huge advantage appears when you start looking at arithmetic
expressions. The result of
if (t < u)
{
x = y + z * w;
}
could be a lot more predictable if we were working with types that
didn't perform implicit lossy conversions.
-- David Abrahams dave_at_[hidden] * http://www.boost-consulting.com Boost support, enhancements, training, and commercial distribution
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk