Sam wrote:
Evan writes:
>Does anyone know of a library that will give me integers with
saturation semantics? E.g. for a signed saturating number, INT_MAX + 1
should give INT_MAX rather than INT_MIN.
Ideally it would be templated (e.g. saturating<unsigned long>), but if
not it's not a big deal.
I don't know of any such library, but writing this kind of a template
should not be very hard.
Really? I see the following problems right away:
a) It is tedious.
b) It is error-prone and you have to provide many tests covering a lot of
corner cases.
c) Deciding how to handle conversions is tricky. Handling them the way you
settled on, is at least as tricky. E.g., should there be conversions
T -saturating<Tand back ?
If T -T' is a conversion,
should saturating<T-saturating<T'be allowed ?
You also need to decide which of those conversions should be explicit and
which should be implicit.
d) Do you want to be standard conforming, or is it ok to rely on
implementation specifics? E.g., the standard leaves it to the
implementation to define a/b and a%b for negative operands. If you are
dealting with signed types, you have to test for overflow _before_ the
operation (otherwise, you have UB). For multiplication, that involves
division and can leads to implementation defined behavior if you do not
take special precautions.
e) What about division? If INT_MAX effectively means infinity, what should
INT_MAX/2 be?
Best
Kai-Uwe Bux