test_checked_cast_constexpr.cpp 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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 <iostream>
  7. #include <boost/safe_numerics/checked_integer.hpp>
  8. // test conversion to T2 from different literal types
  9. template<class T2, class T1>
  10. constexpr bool test_cast_constexpr(
  11. const T1 & v1,
  12. char result
  13. ){
  14. const boost::safe_numerics::checked_result<T2> r2 =
  15. boost::safe_numerics::checked::cast<T2>(v1);
  16. return ('x' == result) ?
  17. r2.exception() :
  18. ! r2.exception();
  19. }
  20. #include "test_checked_cast.hpp"
  21. #include <boost/mp11/algorithm.hpp> // mp_iota
  22. #include <boost/mp11/list.hpp> // mp_first, mp_second, mp_size, mp_is_list
  23. using namespace boost::mp11;
  24. // given a list of integral constants I, return a list of values
  25. template<typename I>
  26. struct get_values {
  27. static_assert(mp_is_list<I>(), "must be a list of two types");
  28. static_assert(2 == mp_size<I>::value, "must be a list of two types");
  29. static constexpr const size_t first = mp_first<I>(); // index of first argument
  30. static constexpr const size_t second = mp_second<I>();// index of second argument
  31. };
  32. template<typename I>
  33. struct test_pair_constexpr {
  34. using pair = get_values<I>;
  35. using TResult = mp_at<test_types, mp_first<I>>;
  36. using TArg = typename mp_at<test_values, mp_second<I>>::value_type;
  37. static constexpr TArg v = mp_at<test_values, mp_second<I>>()();
  38. static constexpr bool value = test_cast_constexpr<TResult>(
  39. v,
  40. test_result_cast[pair::first][pair::second]
  41. );
  42. };
  43. int main(){
  44. // list of indices for values (integral constants)
  45. using value_indices = mp_iota_c<mp_size<test_values>::value>;
  46. // list of indices for types (integral constants)
  47. using type_indices = mp_iota_c<mp_size<test_types>::value>;
  48. // all combinations of type index, value index
  49. using index_pairs = mp_product<mp_list, type_indices, value_indices>;
  50. // test all type/value pairs to verify that cast can be done.
  51. static_assert(
  52. mp_all_of<index_pairs, test_pair_constexpr>::value,
  53. "all type/value pairs correctly cast"
  54. );
  55. return 0;
  56. }