
Boost : 
From: John Maddock (john_at_[hidden])
Date: 20080104 11:45:04
Neil Groves wrote:
> In the case of template functions where you have template<class T> T
> foo(T
> x) { return x = 1; }, I like to use (when I remember!)
> boost::numeric_cast since T might be smaller than int. That is,
> template<class T> T foo(T x) { return x = numeric_cast<T>(1); }
Right but that may throw: IMO a user is going to very surprised indeed if
your code throws when converting a literal :)
However, depending where the integer has come from a numeric_cast may well
be in order.
> I think I'm probably being pedantic but as I recall the size of int
> is not stated as part of the C++ specification, only in relative
> terms to other types. Therefore mixing ints with floatingpoint types
> is not guaranteed to be lossless, although on most implementations it
> will be.
Absolutely, the obvious one is a long long converted to double may loose
digits.
However, in the case of interval arithmetic, at least the converted value
(even if the conversion is implicit as part of an operation) is converted to
an interval that correctly identifies the uncertainty in the value.
But... I'll admit that my use case is exclusively related to the use of
constants: in this case there is simply no better way of representing those
constants than as integers  and yes possibly as long long's  I could
convert them to floating point values, but that would simply introduce the
"inexactness" at an earlier stage. At least if they are encoded as integers
there is a *chance* that they will be used exactly: for example if you are
using extended precision arithmetic.
Regards, John.
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk