example83.cpp 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. #include <iostream>
  2. #include <boost/safe_numerics/safe_integer_range.hpp>
  3. #include <boost/safe_numerics/safe_integer_literal.hpp>
  4. #include <boost/safe_numerics/exception.hpp>
  5. #include <boost/safe_numerics/native.hpp>
  6. #include "safe_format.hpp" // prints out range and value of any type
  7. using namespace boost::safe_numerics;
  8. // create a type for holding small integers in a specific range
  9. using safe_t = safe_signed_range<
  10. -24,
  11. 82,
  12. native, // C++ type promotion rules work OK for this example
  13. loose_trap_policy // catch problems at compile time
  14. >;
  15. // create a type to hold one specific value
  16. template<int I>
  17. using const_safe_t = safe_signed_literal<I, native, loose_trap_policy>;
  18. // We "know" that C++ type promotion rules will work such that
  19. // addition will never overflow. If we change the program to break this,
  20. // the usage of the loose_trap_policy promotion policy will prevent compilation.
  21. int main(int, const char *[]){
  22. std::cout << "example 83:\n";
  23. constexpr const const_safe_t<10> x;
  24. std::cout << "x = " << safe_format(x) << std::endl;
  25. constexpr const const_safe_t<67> y;
  26. std::cout << "y = " << safe_format(y) << std::endl;
  27. const safe_t z = x + y;
  28. std::cout << "x + y = " << safe_format(x + y) << std::endl;
  29. std::cout << "z = " << safe_format(z) << std::endl;
  30. return 0;
  31. }