narrow_cast.hpp 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. /* Copyright 2022 Joaquin M Lopez Munoz.
  2. * Distributed under the Boost Software License, Version 1.0.
  3. * (See accompanying file LICENSE_1_0.txt or copy at
  4. * http://www.boost.org/LICENSE_1_0.txt)
  5. *
  6. * See https://www.boost.org/libs/unordered for library home page.
  7. */
  8. #ifndef BOOST_UNORDERED_DETAIL_NARROW_CAST_HPP
  9. #define BOOST_UNORDERED_DETAIL_NARROW_CAST_HPP
  10. #include <boost/unordered/detail/static_assert.hpp>
  11. #include <boost/config.hpp>
  12. #include <type_traits>
  13. namespace boost{
  14. namespace unordered{
  15. namespace detail{
  16. template<typename To,typename From>
  17. constexpr To narrow_cast(From x) noexcept
  18. {
  19. BOOST_UNORDERED_STATIC_ASSERT(std::is_integral<From>::value);
  20. BOOST_UNORDERED_STATIC_ASSERT(std::is_integral<To>::value);
  21. BOOST_UNORDERED_STATIC_ASSERT(sizeof(From)>=sizeof(To));
  22. return static_cast<To>(
  23. x
  24. #if defined(__MSVC_RUNTIME_CHECKS)
  25. /* Avoids VS's "Run-Time Check Failure #1 - A cast to a smaller data type
  26. * has caused a loss of data."
  27. */
  28. &static_cast<typename std::make_unsigned<To>::type>(~static_cast<To>(0))
  29. #endif
  30. );
  31. }
  32. } /* namespace detail */
  33. } /* namespace unordered */
  34. } /* namespace boost */
  35. #endif