1 #ifndef BOOST_NUMERIC_CHECKED_RESULT
2 #define BOOST_NUMERIC_CHECKED_RESULT
4 // Copyright (c) 2012 Robert Ramey
6 // Distributed under the Boost Software License, Version 1.0. (See
7 // accompanying file LICENSE_1_0.txt or copy at
8 // http://www.boost.org/LICENSE_1_0.txt)
10 // contains operations for doing checked aritmetic on NATIVE
13 #include <type_traits> // is_convertible
14 #include "exception.hpp"
17 namespace safe_numerics {
20 struct checked_result {
21 const safe_numerics_error m_e;
27 // don't permit construction without initial value;
28 checked_result() = delete;
30 // note: I implemented the following non-default copy and move
31 // constructors because I thought I needed to do this in order
32 // to make them constexpr. Turns out though that doing this creates
33 // a syntax error because the assignment results in error due
34 // to assignment "outside of object lifetime". I think this could
35 // be addressed by replacing the anonymous union above with a
36 // named union. This would create some syntax changes which would
37 // ripple through some parts of th program. So for now, we'll just
38 // rely on the default copy and move constructors.
41 constexpr /*explicit*/ checked_result(const checked_result & r) noexpect :
44 if(safe_numerics_error::success == r.m_e)
51 constexpr /*explicit*/ checked_result(checked_result && r) noexcept :
54 if(safe_numerics_error::success == r.m_e)
61 checked_result(const checked_result & r) = default;
62 checked_result(checked_result && r) = default;
64 constexpr /*explicit*/ checked_result(const R & r) noexcept :
65 m_e(safe_numerics_error::success),
69 constexpr /*explicit*/ checked_result(
70 const safe_numerics_error & e,
76 assert(m_e != safe_numerics_error::success);
79 // permit construct from another checked result type
81 constexpr /*explicit*/ checked_result(const checked_result<T> & t) noexcept :
85 std::is_convertible<T, R>::value,
86 "T must be convertible to R"
88 if(safe_numerics_error::success == t.m_e)
94 constexpr bool exception() const {
95 return m_e != safe_numerics_error::success;
99 constexpr operator R() const noexcept{
100 // don't assert here. Let the library catch these errors
101 // assert(! exception());
105 constexpr operator safe_numerics_error () const noexcept{
106 // note that this is a legitimate operation even when
107 // the operation was successful - it will return success
110 constexpr operator const char *() const noexcept{
115 // disallow assignment
116 checked_result & operator=(const checked_result &) = delete;
120 class make_checked_result {
122 template<safe_numerics_error E>
123 constexpr static checked_result<R> invoke(
124 char const * const & m
126 return checked_result<R>(E, m);
133 #endif // BOOST_NUMERIC_CHECKED_RESULT