type_name.hpp 2.2 KB

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