]>
Commit | Line | Data |
---|---|---|
20effc67 TL |
1 | // Copyright (c) 2018 Robert Ramey |
2 | // | |
3 | // Distributed under the Boost Software License, Version 1.0. (See | |
4 | // accompanying file LICENSE_1_0.txt or copy at | |
5 | // http://www.boost.org/LICENSE_1_0.txt) | |
6 | ||
92f5a8d4 TL |
7 | #include <iostream> |
8 | ||
9 | #include <boost/safe_numerics/safe_integer_range.hpp> | |
10 | #include <boost/safe_numerics/safe_integer_literal.hpp> | |
11 | #include <boost/safe_numerics/exception.hpp> | |
12 | #include <boost/safe_numerics/native.hpp> | |
13 | #include "safe_format.hpp" // prints out range and value of any type | |
14 | ||
15 | using namespace boost::safe_numerics; | |
16 | ||
17 | // create a type for holding small integers in a specific range | |
18 | using safe_t = safe_signed_range< | |
19 | -24, | |
20 | 82, | |
21 | native, // C++ type promotion rules work OK for this example | |
22 | loose_trap_policy // catch problems at compile time | |
23 | >; | |
24 | ||
25 | // create a type to hold one specific value | |
26 | template<int I> | |
27 | using const_safe_t = safe_signed_literal<I, native, loose_trap_policy>; | |
28 | ||
29 | // We "know" that C++ type promotion rules will work such that | |
30 | // addition will never overflow. If we change the program to break this, | |
31 | // the usage of the loose_trap_policy promotion policy will prevent compilation. | |
32 | int main(int, const char *[]){ | |
33 | std::cout << "example 83:\n"; | |
34 | ||
35 | constexpr const const_safe_t<10> x; | |
36 | std::cout << "x = " << safe_format(x) << std::endl; | |
37 | constexpr const const_safe_t<67> y; | |
38 | std::cout << "y = " << safe_format(y) << std::endl; | |
20effc67 TL |
39 | auto zx = x + y; |
40 | const safe_t z = zx; | |
41 | //auto z = x + y; | |
92f5a8d4 TL |
42 | std::cout << "x + y = " << safe_format(x + y) << std::endl; |
43 | std::cout << "z = " << safe_format(z) << std::endl; | |
44 | return 0; | |
45 | } |