Imported Upstream version 1.72.0
[platform/upstream/boost.git] / boost / histogram / detail / try_cast.hpp
1 // Copyright 2019 Hans Dembinski
2 //
3 // Distributed under the Boost Software License, Version 1.0.
4 // (See accompanying file LICENSE_1_0.txt
5 // or copy at http://www.boost.org/LICENSE_1_0.txt)
6
7 #ifndef BOOST_HISTOGRAM_DETAIL_TRY_CAST_HPP
8 #define BOOST_HISTOGRAM_DETAIL_TRY_CAST_HPP
9
10 #include <boost/config.hpp>
11 #include <boost/core/demangle.hpp>
12 #include <boost/histogram/detail/type_name.hpp>
13 #include <boost/mp11/integral.hpp>
14 #include <boost/throw_exception.hpp>
15 #include <stdexcept>
16 #include <string>
17 #include <type_traits>
18
19 namespace boost {
20 namespace histogram {
21 namespace detail {
22 template <class T, class E, class U>
23 BOOST_NORETURN T try_cast_impl(mp11::mp_int<0>, U&&) {
24   BOOST_THROW_EXCEPTION(E("cannot cast " + type_name<T>() + " to " + type_name<U>()));
25 }
26
27 template <class T, class E, class U>
28 T try_cast_impl(mp11::mp_int<1>, U&& u) noexcept {
29   return static_cast<T>(u);
30 }
31
32 template <class T, class E, class U>
33 decltype(auto) try_cast_impl(mp11::mp_int<2>, U&& u) noexcept {
34   return std::forward<U>(u);
35 }
36
37 // cast fails at runtime with exception E instead of compile-time, T must be a value
38 template <class T, class E, class U>
39 decltype(auto) try_cast(U&& u) noexcept(std::is_convertible<U, T>::value) {
40   return try_cast_impl<T, E>(mp11::mp_int<(std::is_convertible<U, T>::value +
41                                            std::is_same<T, std::decay_t<U>>::value)>{},
42                              std::forward<U>(u));
43 }
44
45 } // namespace detail
46 } // namespace histogram
47 } // namespace boost
48
49 #endif