example84.cpp 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. #include <stdexcept>
  2. #include <iostream>
  3. #include <boost/safe_numerics/safe_integer.hpp>
  4. #include <boost/safe_numerics/safe_integer_range.hpp>
  5. #include <boost/safe_numerics/automatic.hpp>
  6. #include <boost/safe_numerics/exception.hpp>
  7. #include "safe_format.hpp" // prints out range and value of any type
  8. using namespace boost::safe_numerics;
  9. using safe_t = safe_signed_range<
  10. -24,
  11. 82,
  12. automatic,
  13. loose_trap_policy
  14. >;
  15. // define variables used for input
  16. using input_safe_t = safe_signed_range<
  17. -24,
  18. 82,
  19. automatic, // we don't need automatic in this case
  20. loose_exception_policy // assignment of out of range value should throw
  21. >;
  22. // function arguments can never be outside of limits
  23. auto f(const safe_t & x, const safe_t & y){
  24. auto z = x + y; // we know that this cannot fail
  25. std::cout << "z = " << safe_format(z) << std::endl;
  26. std::cout << "(x + y) = " << safe_format(x + y) << std::endl;
  27. std::cout << "(x - y) = " << safe_format(x - y) << std::endl;
  28. return z;
  29. }
  30. int main(int argc, const char * argv[]){
  31. std::cout << "example 84:\n";
  32. input_safe_t x, y;
  33. try{
  34. std::cout << "type in values in format x y:" << std::flush;
  35. std::cin >> x >> y; // read varibles, maybe throw exception
  36. }
  37. catch(const std::exception & e){
  38. // none of the above should trap. Mark failure if they do
  39. std::cout << e.what() << std::endl;
  40. return 1;
  41. }
  42. std::cout << "x" << safe_format(x) << std::endl;
  43. std::cout << "y" << safe_format(y) << std::endl;
  44. std::cout << safe_format(f(x, y)) << std::endl;
  45. return 0;
  46. }