• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 #include <iostream>
2 #include <limits>
3 
4 #include <boost/rational.hpp>
5 #include <boost/safe_numerics/safe_integer.hpp>
6 
main(int,const char * [])7 int main(int, const char *[]){
8     // simple demo of rational library
9     const boost::rational<int> r {1, 2};
10     std::cout << "r = " << r << std::endl;
11     const boost::rational<int> q {-2, 4};
12     std::cout << "q = " << q << std::endl;
13     // display the product
14     std::cout << "r * q = " << r * q << std::endl;
15 
16     // problem: rational doesn't handle integer overflow well
17     const boost::rational<int> c {1, INT_MAX};
18     std::cout << "c = " << c << std::endl;
19     const boost::rational<int> d {1, 2};
20     std::cout << "d = " << d << std::endl;
21     // display the product - wrong answer
22     std::cout << "c * d = " << c * d << std::endl;
23 
24     // solution: use safe integer in rational definition
25     using safe_rational = boost::rational<
26         boost::safe_numerics::safe<int>
27     >;
28 
29     // use rationals created with safe_t
30     const safe_rational sc {1, INT_MAX};
31     std::cout << "c = " << sc << std::endl;
32     const safe_rational sd {1, 2};
33     std::cout << "d = " << sd << std::endl;
34     std::cout << "c * d = ";
35     try {
36         // multiply them. This will overflow
37         std::cout << sc * sd << std::endl;
38     }
39     catch (std::exception const& e) {
40         // catch exception due to multiplication overflow
41         std::cout << e.what() << std::endl;
42     }
43 
44     return 0;
45 }
46