1 // Copyright 2019 Hans Dembinski
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)
7 #ifndef BOOST_HISTOGRAM_DETAIL_TRY_CAST_HPP
8 #define BOOST_HISTOGRAM_DETAIL_TRY_CAST_HPP
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>
17 #include <type_traits>
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>()));
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);
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);
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)>{},
46 } // namespace histogram