test_constexpr.cpp 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. // Copyright (c) 2014 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. //
  7. // Test constexpr operations on literals
  8. #include <iostream>
  9. #include <boost/safe_numerics/safe_integer_literal.hpp>
  10. #include <boost/safe_numerics/native.hpp>
  11. #include <boost/safe_numerics/exception.hpp>
  12. using namespace boost::safe_numerics;
  13. template<std::uintmax_t N>
  14. using compile_time_value = safe_unsigned_literal<N, native, loose_trap_policy>;
  15. int main(){
  16. constexpr const compile_time_value<1000> x;
  17. constexpr const compile_time_value<1> y;
  18. // should compile and execute without problem
  19. std::cout << x << '\n';
  20. // all the following statements should compile
  21. constexpr auto x_plus_y = x + y;
  22. static_assert(1001 == x_plus_y, "1001 == x + y");
  23. constexpr auto x_minus_y = x - y;
  24. static_assert(999 == x_minus_y, "999 == x - y");
  25. constexpr auto x_times_y = x * y;
  26. static_assert(1000 == x_times_y, "1000 == x * y");
  27. constexpr auto x_and_y = x & y;
  28. static_assert(0 == x_and_y, "0 == x & y");
  29. constexpr auto x_or_y = x | y;
  30. static_assert(1001 == x_or_y, "1001 == x | y");
  31. constexpr auto x_xor_y = x ^ y;
  32. static_assert(1001 == x_xor_y, "1001 == x ^ y");
  33. constexpr auto x_divided_by_y = x / y;
  34. static_assert(1000 == x_divided_by_y, "1000 == x / y");
  35. constexpr auto x_mod_y = x % y;
  36. static_assert(0 == x_mod_y, "0 == x % y");
  37. // this should fail compilation since a positive unsigned number
  38. // can't be converted to a negative value of the same type
  39. constexpr auto minus_x = -x;
  40. // should compile OK since the negative inverse of a zero is still zero
  41. constexpr const compile_time_value<0> x0;
  42. constexpr auto minus_x0 = -x0; // should compile OK
  43. static_assert(0 == minus_x0, "0 == -x where x == 0");
  44. constexpr auto not_x = ~x;
  45. return 0;
  46. }