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