| 1 | /* |
| 2 | @file |
| 3 | Defines `boost::hana::experimental::type_name`. |
| 4 | |
| 5 | Copyright Louis Dionne 2013-2022 |
| 6 | Distributed under the Boost Software License, Version 1.0. |
| 7 | (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) |
| 8 | */ |
| 9 | |
| 10 | #ifndef BOOST_HANA_EXPERIMENTAL_TYPE_NAME_HPP |
| 11 | #define BOOST_HANA_EXPERIMENTAL_TYPE_NAME_HPP |
| 12 | |
| 13 | #include <boost/hana/config.hpp> |
| 14 | #include <boost/hana/string.hpp> |
| 15 | |
| 16 | #include <cstddef> |
| 17 | #include <utility> |
| 18 | |
| 19 | |
| 20 | namespace boost { namespace hana { namespace experimental { |
| 21 | namespace detail { |
| 22 | struct cstring { |
| 23 | char const* ptr; |
| 24 | std::size_t length; |
| 25 | }; |
| 26 | |
| 27 | // Note: We substract the null terminator from the string sizes below. |
| 28 | template <typename T> |
| 29 | constexpr auto type_name_impl2() { |
| 30 | #if defined(BOOST_HANA_CONFIG_CLANG) |
| 31 | constexpr char const* pretty_function = __PRETTY_FUNCTION__; |
| 32 | constexpr std::size_t total_size = sizeof(__PRETTY_FUNCTION__) - 1; |
| 33 | constexpr std::size_t prefix_size = sizeof("auto boost::hana::experimental::detail::type_name_impl2() [T = " ) - 1; |
| 34 | constexpr std::size_t suffix_size = sizeof("]" ) - 1; |
| 35 | #elif defined(BOOST_HANA_CONFIG_GCC) |
| 36 | constexpr char const* pretty_function = __PRETTY_FUNCTION__; |
| 37 | constexpr std::size_t total_size = sizeof(__PRETTY_FUNCTION__) - 1; |
| 38 | constexpr std::size_t prefix_size = sizeof("constexpr auto boost::hana::experimental::detail::type_name_impl2() [with T = " ) - 1; |
| 39 | constexpr std::size_t suffix_size = sizeof("]" ) - 1; |
| 40 | #else |
| 41 | #error "No support for this compiler." |
| 42 | #endif |
| 43 | |
| 44 | cstring s{.ptr: pretty_function + prefix_size, .length: total_size - prefix_size - suffix_size}; |
| 45 | return s; |
| 46 | } |
| 47 | |
| 48 | template <typename T, std::size_t ...i> |
| 49 | auto type_name_impl1(std::index_sequence<i...>) { |
| 50 | constexpr auto name = detail::type_name_impl2<T>(); |
| 51 | return hana::string<*(name.ptr + i)...>{}; |
| 52 | } |
| 53 | } // end namespace detail |
| 54 | |
| 55 | //! @ingroup group-experimental |
| 56 | //! Returns a `hana::string` representing the name of the given type, at |
| 57 | //! compile-time. |
| 58 | //! |
| 59 | //! This only works on Clang (and apparently MSVC, but Hana does not work |
| 60 | //! there as of writing this). Original idea taken from |
| 61 | //! https://github.com/Manu343726/ctti. |
| 62 | template <typename T> |
| 63 | auto type_name() { |
| 64 | constexpr auto name = detail::type_name_impl2<T>(); |
| 65 | return detail::type_name_impl1<T>(std::make_index_sequence<name.length>{}); |
| 66 | } |
| 67 | } }} // end namespace boost::hana |
| 68 | |
| 69 | #endif // !BOOST_HANA_EXPERIMENTAL_TYPE_NAME_HPP |
| 70 | |