test_checked_divide_constexpr.cpp 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. // Copyright (c) 2012 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. #include <cstdint> // std::int8, ...
  7. #include <boost/safe_numerics/checked_result.hpp>
  8. #include <boost/safe_numerics/checked_result_operations.hpp>
  9. #include <boost/safe_numerics/checked_integer.hpp>
  10. // note: T should be of tyme checked_result<R> for some integer type R
  11. template<class T>
  12. constexpr bool test_checked_divide(
  13. const T & v1,
  14. const T & v2,
  15. char expected_result
  16. ){
  17. using namespace boost::safe_numerics;
  18. const T result = v1 / v2;
  19. switch(expected_result){
  20. case '0':
  21. case '.':
  22. return ! result.exception();
  23. case '-':
  24. return safe_numerics_error::negative_overflow_error == result.m_e;
  25. case '+':
  26. return safe_numerics_error::positive_overflow_error == result.m_e;
  27. case '!':
  28. return safe_numerics_error::range_error == result.m_e;
  29. }
  30. return false;
  31. }
  32. #include "test_checked_divide.hpp"
  33. template<typename T, typename First, typename Second>
  34. struct test_signed_pair {
  35. static const std::size_t i = First();
  36. static const std::size_t j = Second();
  37. // note: is constexpr really required here? compilers disagree!
  38. constexpr static const bool value = test_checked_divide(
  39. signed_values<T>[i],
  40. signed_values<T>[j],
  41. signed_division_results[i][j]
  42. );
  43. };
  44. template<typename T, typename First, typename Second>
  45. struct test_unsigned_pair {
  46. static const std::size_t i = First();
  47. static const std::size_t j = Second();
  48. // note: is constexpr really required here? compilers disagree!
  49. constexpr static const bool value = test_checked_divide(
  50. unsigned_values<T>[i],
  51. unsigned_values<T>[j],
  52. unsigned_division_results[i][j]
  53. );
  54. };
  55. #include <boost/mp11/algorithm.hpp>
  56. #include <boost/mp11/function.hpp>
  57. int main(){
  58. using namespace boost::mp11;
  59. static_assert(
  60. mp_all_of<
  61. mp_product<
  62. test_signed_pair,
  63. signed_test_types,
  64. signed_value_indices, signed_value_indices
  65. >,
  66. mp_to_bool
  67. >(),
  68. "all values for all signed types correctly divided"
  69. );
  70. static_assert(
  71. mp_all_of<
  72. mp_product<
  73. test_unsigned_pair,
  74. unsigned_test_types,
  75. unsigned_value_indices, unsigned_value_indices
  76. >,
  77. mp_to_bool
  78. >(),
  79. "all values for all unsigned types correctly divided"
  80. );
  81. return 0;
  82. }