
Boost : 
From: Andy Little (andy_at_[hidden])
Date: 20050317 07:18:43
"Aleksey Gurtovoy" <agurtovoy_at_[hidden]> wrote
> Andy Little writes:
>> The solution: A new operator... mpl::rational_divides<A,B> When it is
>> desired not to truncate, this form will preserve the fractional part
>> by if necessary converting to a rational number. With this operator in
>> place it is also possible to 'reduce' rationals to integers where
>> possible and further to keep integral constants as integral types by
>> default, knowing that conversion will be automatic if a fraction is
>> required to prevent loss of precision.
>>
>
> Could you provide a specific use case where the above would be preferable
> over something like
>
> mpl::divide< to_rational<A>,B >
>
> ?
That seems like a good solution. :) though rational_divides<A,B> is slightly
less typing.
> Why one would prefer to have a separate metafunction for
> doing the right thing instead of simply overriding the standard one?
Is 1/2 == 0 'the right thing'? Integer division is one operation where a
silent loss of information occurs with no warning. I think I would prefer
divides<int_<1>,int_<2> > to return a rational<1,2>. (which incidentally would
seamlessly integrate rationals and integers and allow the automatic reduction) .
However to preserve the statusquo, a new function name could be used where
nontruncating behaviour is required irrespective of type; as well as a
quotient_of_divides which always truncates, a careful_divides function which
verifies that no truncation has occurred, etc.
The original reason for wanting this behaviour was in exponents for dimensional
analysis. Rationals are required to cover rare cases. As well as some presumed
effect on compilation time, the other effect of using rationals over integers is
to lengthen the signature of the Dimension type, which affects legibility of
error messages, just for the sake of these few rare cases. This was the
rationale behind automatically 'reducing' rationals to integral types where
possible, thus easing use of integrals in definitions of Dimension types,
however the knock on effect was that division on two 'reduced' rationals would
simply be division on two integral types( with quiet truncation). Hence the name
change.
FWIW the automatic reduction of rational to integral was problematic due to the
above issues. The idea of 'reducing' rationals to integer types where possible
is still attractive, but making the cast explicit eg via a
to_integral_if_possible<T> function.
regards
Andy Little
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk