core_name.hpp 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. // Copyright (c) 2023 Bela Schaum, X-Ryl669, Denis Mikhailov.
  2. //
  3. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  4. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  5. // Initial implementation by Bela Schaum, https://github.com/schaumb
  6. // The way to make it union and UB free by X-Ryl669, https://github.com/X-Ryl669
  7. //
  8. #ifndef BOOST_PFR_CORE_NAME_HPP
  9. #define BOOST_PFR_CORE_NAME_HPP
  10. #pragma once
  11. #include <boost/pfr/detail/config.hpp>
  12. #include <boost/pfr/detail/core_name.hpp>
  13. #include <boost/pfr/detail/sequence_tuple.hpp>
  14. #include <boost/pfr/detail/stdarray.hpp>
  15. #include <boost/pfr/detail/make_integer_sequence.hpp>
  16. #include <cstddef> // for std::size_t
  17. #include <boost/pfr/tuple_size.hpp>
  18. /// \file boost/pfr/core_name.hpp
  19. /// Contains functions \forcedlink{get_name} and \forcedlink{names_as_array} to know which names each field of any \aggregate has.
  20. ///
  21. /// \fnrefl for details.
  22. ///
  23. /// \b Synopsis:
  24. namespace boost { namespace pfr {
  25. /// \brief Returns name of a field with index `I` in \aggregate `T`.
  26. ///
  27. /// \b Example:
  28. /// \code
  29. /// struct my_struct { int i, short s; };
  30. ///
  31. /// assert(boost::pfr::get_name<0, my_struct>() == "i");
  32. /// assert(boost::pfr::get_name<1, my_struct>() == "s");
  33. /// \endcode
  34. template <std::size_t I, class T>
  35. constexpr
  36. #ifdef BOOST_PFR_DOXYGEN_INVOKED
  37. std::string_view
  38. #else
  39. auto
  40. #endif
  41. get_name() noexcept {
  42. return detail::get_name<T, I>();
  43. }
  44. // FIXME: implement this
  45. // template<class U, class T>
  46. // constexpr auto get_name() noexcept {
  47. // return detail::sequence_tuple::get_by_type_impl<U>( detail::tie_as_names_tuple<T>() );
  48. // }
  49. /// \brief Creates a `std::array` from names of fields of an \aggregate `T`.
  50. ///
  51. /// \b Example:
  52. /// \code
  53. /// struct my_struct { int i, short s; };
  54. /// std::array<std::string_view, 2> a = boost::pfr::names_as_array<my_struct>();
  55. /// assert(a[0] == "i");
  56. /// \endcode
  57. template <class T>
  58. constexpr
  59. #ifdef BOOST_PFR_DOXYGEN_INVOKED
  60. std::array<std::string_view, boost::pfr::tuple_size_v<T>>
  61. #else
  62. auto
  63. #endif
  64. names_as_array() noexcept {
  65. return detail::make_stdarray_from_tietuple(
  66. detail::tie_as_names_tuple<T>(),
  67. detail::make_index_sequence< tuple_size_v<T> >(),
  68. 1L
  69. );
  70. }
  71. }} // namespace boost::pfr
  72. #endif // BOOST_PFR_CORE_NAME_HPP