test_checked_subtract_constexpr.cpp 2.6 KB

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