fields_count.hpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. // Copyright (c) 2016-2021 Antony Polukhin
  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. #ifndef BOOST_PFR_DETAIL_FIELDS_COUNT_HPP
  6. #define BOOST_PFR_DETAIL_FIELDS_COUNT_HPP
  7. #pragma once
  8. #include <boost/pfr/detail/config.hpp>
  9. #include <boost/pfr/detail/make_integer_sequence.hpp>
  10. #include <boost/pfr/detail/size_t_.hpp>
  11. #include <boost/pfr/detail/unsafe_declval.hpp>
  12. #include <climits> // CHAR_BIT
  13. #include <type_traits>
  14. #include <utility> // metaprogramming stuff
  15. #ifdef __clang__
  16. # pragma clang diagnostic push
  17. # pragma clang diagnostic ignored "-Wmissing-braces"
  18. # pragma clang diagnostic ignored "-Wundefined-inline"
  19. # pragma clang diagnostic ignored "-Wundefined-internal"
  20. # pragma clang diagnostic ignored "-Wmissing-field-initializers"
  21. #endif
  22. namespace boost { namespace pfr { namespace detail {
  23. ///////////////////// Structure that can be converted to reference to anything
  24. struct ubiq_lref_constructor {
  25. std::size_t ignore;
  26. template <class Type> constexpr operator Type&() const && noexcept { // tweak for template_unconstrained.cpp like cases
  27. return detail::unsafe_declval<Type&>();
  28. };
  29. template <class Type> constexpr operator Type&() const & noexcept { // tweak for optional_chrono.cpp like cases
  30. return detail::unsafe_declval<Type&>();
  31. };
  32. };
  33. ///////////////////// Structure that can be converted to rvalue reference to anything
  34. struct ubiq_rref_constructor {
  35. std::size_t ignore;
  36. template <class Type> /*constexpr*/ operator Type&&() const && noexcept { // Allows initialization of rvalue reference fields and move-only types
  37. return detail::unsafe_declval<Type&&>();
  38. };
  39. };
  40. #ifndef __cpp_lib_is_aggregate
  41. ///////////////////// Hand-made is_aggregate_initializable_n<T> trait
  42. // Structure that can be converted to reference to anything except reference to T
  43. template <class T, bool IsCopyConstructible>
  44. struct ubiq_constructor_except {
  45. std::size_t ignore;
  46. template <class Type> constexpr operator std::enable_if_t<!std::is_same<T, Type>::value, Type&> () const noexcept; // Undefined
  47. };
  48. template <class T>
  49. struct ubiq_constructor_except<T, false> {
  50. std::size_t ignore;
  51. template <class Type> constexpr operator std::enable_if_t<!std::is_same<T, Type>::value, Type&&> () const noexcept; // Undefined
  52. };
  53. // `std::is_constructible<T, ubiq_constructor_except<T>>` consumes a lot of time, so we made a separate lazy trait for it.
  54. template <std::size_t N, class T> struct is_single_field_and_aggregate_initializable: std::false_type {};
  55. template <class T> struct is_single_field_and_aggregate_initializable<1, T>: std::integral_constant<
  56. bool, !std::is_constructible<T, ubiq_constructor_except<T, std::is_copy_constructible<T>::value>>::value
  57. > {};
  58. // Hand-made is_aggregate<T> trait:
  59. // Before C++20 aggregates could be constructed from `decltype(ubiq_?ref_constructor{I})...` but type traits report that
  60. // there's no constructor from `decltype(ubiq_?ref_constructor{I})...`
  61. // Special case for N == 1: `std::is_constructible<T, ubiq_?ref_constructor>` returns true if N == 1 and T is copy/move constructible.
  62. template <class T, std::size_t N>
  63. struct is_aggregate_initializable_n {
  64. template <std::size_t ...I>
  65. static constexpr bool is_not_constructible_n(std::index_sequence<I...>) noexcept {
  66. return (!std::is_constructible<T, decltype(ubiq_lref_constructor{I})...>::value && !std::is_constructible<T, decltype(ubiq_rref_constructor{I})...>::value)
  67. || is_single_field_and_aggregate_initializable<N, T>::value
  68. ;
  69. }
  70. static constexpr bool value =
  71. std::is_empty<T>::value
  72. || std::is_array<T>::value
  73. || std::is_fundamental<T>::value
  74. || is_not_constructible_n(detail::make_index_sequence<N>{})
  75. ;
  76. };
  77. #endif // #ifndef __cpp_lib_is_aggregate
  78. ///////////////////// Helper for SFINAE on fields count
  79. template <class T, std::size_t... I, class /*Enable*/ = typename std::enable_if<std::is_copy_constructible<T>::value>::type>
  80. constexpr auto enable_if_constructible_helper(std::index_sequence<I...>) noexcept
  81. -> typename std::add_pointer<decltype(T{ ubiq_lref_constructor{I}... })>::type;
  82. template <class T, std::size_t... I, class /*Enable*/ = typename std::enable_if<!std::is_copy_constructible<T>::value>::type>
  83. constexpr auto enable_if_constructible_helper(std::index_sequence<I...>) noexcept
  84. -> typename std::add_pointer<decltype(T{ ubiq_rref_constructor{I}... })>::type;
  85. template <class T, std::size_t N, class /*Enable*/ = decltype( enable_if_constructible_helper<T>(detail::make_index_sequence<N>()) ) >
  86. using enable_if_constructible_helper_t = std::size_t;
  87. ///////////////////// Helpers for range size detection
  88. template <std::size_t Begin, std::size_t Last>
  89. using is_one_element_range = std::integral_constant<bool, Begin == Last>;
  90. using multi_element_range = std::false_type;
  91. using one_element_range = std::true_type;
  92. ///////////////////// Non greedy fields count search. Templates instantiation depth is log(sizeof(T)), templates instantiation count is log(sizeof(T)).
  93. template <class T, std::size_t Begin, std::size_t Middle>
  94. constexpr std::size_t detect_fields_count(detail::one_element_range, long) noexcept {
  95. static_assert(
  96. Begin == Middle,
  97. "====================> Boost.PFR: Internal logic error."
  98. );
  99. return Begin;
  100. }
  101. template <class T, std::size_t Begin, std::size_t Middle>
  102. constexpr std::size_t detect_fields_count(detail::multi_element_range, int) noexcept;
  103. template <class T, std::size_t Begin, std::size_t Middle>
  104. constexpr auto detect_fields_count(detail::multi_element_range, long) noexcept
  105. -> detail::enable_if_constructible_helper_t<T, Middle>
  106. {
  107. constexpr std::size_t next_v = Middle + (Middle - Begin + 1) / 2;
  108. return detail::detect_fields_count<T, Middle, next_v>(detail::is_one_element_range<Middle, next_v>{}, 1L);
  109. }
  110. template <class T, std::size_t Begin, std::size_t Middle>
  111. constexpr std::size_t detect_fields_count(detail::multi_element_range, int) noexcept {
  112. constexpr std::size_t next_v = Begin + (Middle - Begin) / 2;
  113. return detail::detect_fields_count<T, Begin, next_v>(detail::is_one_element_range<Begin, next_v>{}, 1L);
  114. }
  115. ///////////////////// Greedy search. Templates instantiation depth is log(sizeof(T)), templates instantiation count is log(sizeof(T))*T in worst case.
  116. template <class T, std::size_t N>
  117. constexpr auto detect_fields_count_greedy_remember(long) noexcept
  118. -> detail::enable_if_constructible_helper_t<T, N>
  119. {
  120. return N;
  121. }
  122. template <class T, std::size_t N>
  123. constexpr std::size_t detect_fields_count_greedy_remember(int) noexcept {
  124. return 0;
  125. }
  126. template <class T, std::size_t Begin, std::size_t Last>
  127. constexpr std::size_t detect_fields_count_greedy(detail::one_element_range) noexcept {
  128. static_assert(
  129. Begin == Last,
  130. "====================> Boost.PFR: Internal logic error."
  131. );
  132. return detail::detect_fields_count_greedy_remember<T, Begin>(1L);
  133. }
  134. template <class T, std::size_t Begin, std::size_t Last>
  135. constexpr std::size_t detect_fields_count_greedy(detail::multi_element_range) noexcept {
  136. constexpr std::size_t middle = Begin + (Last - Begin) / 2;
  137. constexpr std::size_t fields_count_big_range = detail::detect_fields_count_greedy<T, middle + 1, Last>(
  138. detail::is_one_element_range<middle + 1, Last>{}
  139. );
  140. constexpr std::size_t small_range_begin = (fields_count_big_range ? 0 : Begin);
  141. constexpr std::size_t small_range_last = (fields_count_big_range ? 0 : middle);
  142. constexpr std::size_t fields_count_small_range = detail::detect_fields_count_greedy<T, small_range_begin, small_range_last>(
  143. detail::is_one_element_range<small_range_begin, small_range_last>{}
  144. );
  145. return fields_count_big_range ? fields_count_big_range : fields_count_small_range;
  146. }
  147. ///////////////////// Choosing between array size, greedy and non greedy search.
  148. template <class T, std::size_t N>
  149. constexpr auto detect_fields_count_dispatch(size_t_<N>, long, long) noexcept
  150. -> typename std::enable_if<std::is_array<T>::value, std::size_t>::type
  151. {
  152. return sizeof(T) / sizeof(typename std::remove_all_extents<T>::type);
  153. }
  154. template <class T, std::size_t N>
  155. constexpr auto detect_fields_count_dispatch(size_t_<N>, long, int) noexcept
  156. -> decltype(sizeof(T{}))
  157. {
  158. constexpr std::size_t middle = N / 2 + 1;
  159. return detail::detect_fields_count<T, 0, middle>(detail::multi_element_range{}, 1L);
  160. }
  161. template <class T, std::size_t N>
  162. constexpr std::size_t detect_fields_count_dispatch(size_t_<N>, int, int) noexcept {
  163. // T is not default aggregate initialzable. It means that at least one of the members is not default constructible,
  164. // so we have to check all the aggregate initializations for T up to N parameters and return the bigest succeeded
  165. // (we can not use binary search for detecting fields count).
  166. return detail::detect_fields_count_greedy<T, 0, N>(detail::multi_element_range{});
  167. }
  168. ///////////////////// Returns fields count
  169. template <class T>
  170. constexpr std::size_t fields_count() noexcept {
  171. using type = std::remove_cv_t<T>;
  172. static_assert(
  173. !std::is_reference<type>::value,
  174. "====================> Boost.PFR: Attempt to get fields count on a reference. This is not allowed because that could hide an issue and different library users expect different behavior in that case."
  175. );
  176. static_assert(
  177. std::is_copy_constructible<std::remove_all_extents_t<type>>::value || (
  178. std::is_move_constructible<std::remove_all_extents_t<type>>::value
  179. && std::is_move_assignable<std::remove_all_extents_t<type>>::value
  180. ),
  181. "====================> Boost.PFR: Type and each field in the type must be copy constructible (or move constructible and move assignable)."
  182. );
  183. static_assert(
  184. !std::is_polymorphic<type>::value,
  185. "====================> Boost.PFR: Type must have no virtual function, because otherwise it is not aggregate initializable."
  186. );
  187. #ifdef __cpp_lib_is_aggregate
  188. static_assert(
  189. std::is_aggregate<type>::value // Does not return `true` for built-in types.
  190. || std::is_scalar<type>::value,
  191. "====================> Boost.PFR: Type must be aggregate initializable."
  192. );
  193. #endif
  194. // Can't use the following. See the non_std_layout.cpp test.
  195. //#if !BOOST_PFR_USE_CPP17
  196. // static_assert(
  197. // std::is_standard_layout<type>::value, // Does not return `true` for structs that have non standard layout members.
  198. // "Type must be aggregate initializable."
  199. // );
  200. //#endif
  201. constexpr std::size_t max_fields_count = (sizeof(type) * CHAR_BIT); // We multiply by CHAR_BIT because the type may have bitfields in T
  202. constexpr std::size_t result = detail::detect_fields_count_dispatch<type>(size_t_<max_fields_count>{}, 1L, 1L);
  203. #ifndef __cpp_lib_is_aggregate
  204. static_assert(
  205. is_aggregate_initializable_n<type, result>::value,
  206. "====================> Boost.PFR: Types with user specified constructors (non-aggregate initializable types) are not supported."
  207. );
  208. #endif
  209. static_assert(
  210. result != 0 || std::is_empty<type>::value || std::is_fundamental<type>::value || std::is_reference<type>::value,
  211. "====================> Boost.PFR: If there's no other failed static asserts then something went wrong. Please report this issue to the github along with the structure you're reflecting."
  212. );
  213. return result;
  214. }
  215. }}} // namespace boost::pfr::detail
  216. #ifdef __clang__
  217. # pragma clang diagnostic pop
  218. #endif
  219. #endif // BOOST_PFR_DETAIL_FIELDS_COUNT_HPP