summaryrefslogtreecommitdiffstats
path: root/src/boost/libs/safe_numerics/example/example15.cpp
diff options
context:
space:
mode:
authorDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-27 18:24:20 +0000
committerDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-27 18:24:20 +0000
commit483eb2f56657e8e7f419ab1a4fab8dce9ade8609 (patch)
treee5d88d25d870d5dedacb6bbdbe2a966086a0a5cf /src/boost/libs/safe_numerics/example/example15.cpp
parentInitial commit. (diff)
downloadceph-upstream.tar.xz
ceph-upstream.zip
Adding upstream version 14.2.21.upstream/14.2.21upstream
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'src/boost/libs/safe_numerics/example/example15.cpp')
-rw-r--r--src/boost/libs/safe_numerics/example/example15.cpp45
1 files changed, 45 insertions, 0 deletions
diff --git a/src/boost/libs/safe_numerics/example/example15.cpp b/src/boost/libs/safe_numerics/example/example15.cpp
new file mode 100644
index 00000000..829dff29
--- /dev/null
+++ b/src/boost/libs/safe_numerics/example/example15.cpp
@@ -0,0 +1,45 @@
+#include <iostream>
+#include <limits>
+
+#include <boost/rational.hpp>
+#include <boost/safe_numerics/safe_integer.hpp>
+
+int main(int, const char *[]){
+ // simple demo of rational library
+ const boost::rational<int> r {1, 2};
+ std::cout << "r = " << r << std::endl;
+ const boost::rational<int> q {-2, 4};
+ std::cout << "q = " << q << std::endl;
+ // display the product
+ std::cout << "r * q = " << r * q << std::endl;
+
+ // problem: rational doesn't handle integer overflow well
+ const boost::rational<int> c {1, INT_MAX};
+ std::cout << "c = " << c << std::endl;
+ const boost::rational<int> d {1, 2};
+ std::cout << "d = " << d << std::endl;
+ // display the product - wrong answer
+ std::cout << "c * d = " << c * d << std::endl;
+
+ // solution: use safe integer in rational definition
+ using safe_rational = boost::rational<
+ boost::safe_numerics::safe<int>
+ >;
+
+ // use rationals created with safe_t
+ const safe_rational sc {1, INT_MAX};
+ std::cout << "c = " << sc << std::endl;
+ const safe_rational sd {1, 2};
+ std::cout << "d = " << sd << std::endl;
+ std::cout << "c * d = ";
+ try {
+ // multiply them. This will overflow
+ std::cout << sc * sd << std::endl;
+ }
+ catch (std::exception const& e) {
+ // catch exception due to multiplication overflow
+ std::cout << e.what() << std::endl;
+ }
+
+ return 0;
+}