Composition with Other Libraries For many years, Boost has included a library to represent and operate on rational numbers. Its well crafted, has good documentation and is well maintained. Using the rational library is as easy as construction an instance with the expression rational r(n, d) where n and d are integers of the same type. From then on it can be used pretty much as any other number. Reading the documentation with safe integers in mind one finds
Limited-precision integer types [such as int] may raise issues with the range sizes of their allowable negative values and positive values. If the negative range is larger, then the extremely-negative numbers will not have an additive inverse in the positive range, making them unusable as denominator values since they cannot be normalized to positive values (unless the user is lucky enough that the input components are not relatively prime pre-normalization).
Which hints of trouble. Examination of the code reveals which suggest that care has been taken implement operations so as to avoid overflows, catch divide by zero, etc. But the code itself doesn't seem to consistently implement this idea. So we make a small demo program: which produces the following outputr = 1/2 q = -1/2 r * q = -1/4 c = 1/2147483647 d = 1/2 c * d = 1/-2 c = 1/2147483647 d = 1/2 c * d = multiplication overflow: positive overflow error
The rational library documentation is quite specific as to the type requirements placed on the underlying type. Turns out the our own definition of an integer type fulfills (actually surpasses) these requirements. So we have reason to hope that we can use safe<int> as the underlying type to create what we might call a "safe_rational". This we have done in the above example where we demonstrate how to compose the rational library with the safe numerics library in order to create what amounts to a safe_rational library - all without writing a line of code! Still, things are not perfect. Since the rational numbers library implements its own checking for divide by zero by throwing an exception, the safe numerics code for handling this - included exception policy will not be respected. To summarize: In some cases safe types can be used as template parameters to other types to inject the concept of "no erroneous results" into the target type. Such composition is not guaranteed to work. The target type must be reviewed in some detail.