fields_count.hpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. // Copyright (c) 2016-2024 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. ///////////////////// Detect aggregates with inheritance
  79. template <class Derived, class U>
  80. constexpr bool static_assert_non_inherited() noexcept {
  81. static_assert(
  82. !std::is_base_of<U, Derived>::value,
  83. "====================> Boost.PFR: Boost.PFR: Inherited types are not supported."
  84. );
  85. return true;
  86. }
  87. template <class Derived>
  88. struct ubiq_lref_base_asserting {
  89. template <class Type> constexpr operator Type&() const && // tweak for template_unconstrained.cpp like cases
  90. noexcept(detail::static_assert_non_inherited<Derived, Type>()) // force the computation of assert function
  91. {
  92. return detail::unsafe_declval<Type&>();
  93. }
  94. template <class Type> constexpr operator Type&() const & // tweak for optional_chrono.cpp like cases
  95. noexcept(detail::static_assert_non_inherited<Derived, Type>()) // force the computation of assert function
  96. {
  97. return detail::unsafe_declval<Type&>();
  98. }
  99. };
  100. template <class Derived>
  101. struct ubiq_rref_base_asserting {
  102. template <class Type> /*constexpr*/ operator Type() const && // Allows initialization of rvalue reference fields and move-only types
  103. noexcept(detail::static_assert_non_inherited<Derived, Type>()) // force the computation of assert function
  104. {
  105. return detail::unsafe_declval<Type>();
  106. }
  107. };
  108. template <class T, std::size_t I0, std::size_t... I, class /*Enable*/ = typename std::enable_if<std::is_copy_constructible<T>::value>::type>
  109. constexpr auto assert_first_not_base(std::index_sequence<I0, I...>) noexcept
  110. -> typename std::add_pointer<decltype(T{ ubiq_lref_base_asserting<T>{}, ubiq_lref_constructor{I}... })>::type
  111. {
  112. return nullptr;
  113. }
  114. template <class T, std::size_t I0, std::size_t... I, class /*Enable*/ = typename std::enable_if<!std::is_copy_constructible<T>::value>::type>
  115. constexpr auto assert_first_not_base(std::index_sequence<I0, I...>) noexcept
  116. -> typename std::add_pointer<decltype(T{ ubiq_rref_base_asserting<T>{}, ubiq_rref_constructor{I}... })>::type
  117. {
  118. return nullptr;
  119. }
  120. template <class T>
  121. constexpr void* assert_first_not_base(std::index_sequence<>) noexcept
  122. {
  123. return nullptr;
  124. }
  125. ///////////////////// Helper for SFINAE on fields count
  126. template <class T, std::size_t... I, class /*Enable*/ = typename std::enable_if<std::is_copy_constructible<T>::value>::type>
  127. constexpr auto enable_if_constructible_helper(std::index_sequence<I...>) noexcept
  128. -> typename std::add_pointer<decltype(T{ ubiq_lref_constructor{I}... })>::type;
  129. template <class T, std::size_t... I, class /*Enable*/ = typename std::enable_if<!std::is_copy_constructible<T>::value>::type>
  130. constexpr auto enable_if_constructible_helper(std::index_sequence<I...>) noexcept
  131. -> typename std::add_pointer<decltype(T{ ubiq_rref_constructor{I}... })>::type;
  132. template <class T, std::size_t N, class /*Enable*/ = decltype( enable_if_constructible_helper<T>(detail::make_index_sequence<N>()) ) >
  133. using enable_if_constructible_helper_t = std::size_t;
  134. ///////////////////// Helpers for range size detection
  135. template <std::size_t Begin, std::size_t Last>
  136. using is_one_element_range = std::integral_constant<bool, Begin == Last>;
  137. using multi_element_range = std::false_type;
  138. using one_element_range = std::true_type;
  139. ///////////////////// Non greedy fields count search. Templates instantiation depth is log(sizeof(T)), templates instantiation count is log(sizeof(T)).
  140. template <class T, std::size_t Begin, std::size_t Middle>
  141. constexpr std::size_t detect_fields_count(detail::one_element_range, long) noexcept {
  142. static_assert(
  143. Begin == Middle,
  144. "====================> Boost.PFR: Internal logic error."
  145. );
  146. return Begin;
  147. }
  148. template <class T, std::size_t Begin, std::size_t Middle>
  149. constexpr std::size_t detect_fields_count(detail::multi_element_range, int) noexcept;
  150. template <class T, std::size_t Begin, std::size_t Middle>
  151. constexpr auto detect_fields_count(detail::multi_element_range, long) noexcept
  152. -> detail::enable_if_constructible_helper_t<T, Middle>
  153. {
  154. constexpr std::size_t next_v = Middle + (Middle - Begin + 1) / 2;
  155. return detail::detect_fields_count<T, Middle, next_v>(detail::is_one_element_range<Middle, next_v>{}, 1L);
  156. }
  157. template <class T, std::size_t Begin, std::size_t Middle>
  158. constexpr std::size_t detect_fields_count(detail::multi_element_range, int) noexcept {
  159. constexpr std::size_t next_v = Begin + (Middle - Begin) / 2;
  160. return detail::detect_fields_count<T, Begin, next_v>(detail::is_one_element_range<Begin, next_v>{}, 1L);
  161. }
  162. ///////////////////// Greedy search. Templates instantiation depth is log(sizeof(T)), templates instantiation count is log(sizeof(T))*T in worst case.
  163. template <class T, std::size_t N>
  164. constexpr auto detect_fields_count_greedy_remember(long) noexcept
  165. -> detail::enable_if_constructible_helper_t<T, N>
  166. {
  167. return N;
  168. }
  169. template <class T, std::size_t N>
  170. constexpr std::size_t detect_fields_count_greedy_remember(int) noexcept {
  171. return 0;
  172. }
  173. template <class T, std::size_t Begin, std::size_t Last>
  174. constexpr std::size_t detect_fields_count_greedy(detail::one_element_range) noexcept {
  175. static_assert(
  176. Begin == Last,
  177. "====================> Boost.PFR: Internal logic error."
  178. );
  179. return detail::detect_fields_count_greedy_remember<T, Begin>(1L);
  180. }
  181. template <class T, std::size_t Begin, std::size_t Last>
  182. constexpr std::size_t detect_fields_count_greedy(detail::multi_element_range) noexcept {
  183. constexpr std::size_t middle = Begin + (Last - Begin) / 2;
  184. constexpr std::size_t fields_count_big_range = detail::detect_fields_count_greedy<T, middle + 1, Last>(
  185. detail::is_one_element_range<middle + 1, Last>{}
  186. );
  187. constexpr std::size_t small_range_begin = (fields_count_big_range ? 0 : Begin);
  188. constexpr std::size_t small_range_last = (fields_count_big_range ? 0 : middle);
  189. constexpr std::size_t fields_count_small_range = detail::detect_fields_count_greedy<T, small_range_begin, small_range_last>(
  190. detail::is_one_element_range<small_range_begin, small_range_last>{}
  191. );
  192. return fields_count_big_range ? fields_count_big_range : fields_count_small_range;
  193. }
  194. ///////////////////// Choosing between array size, greedy and non greedy search.
  195. template <class T, std::size_t N>
  196. constexpr auto detect_fields_count_dispatch(size_t_<N>, long, long) noexcept
  197. -> typename std::enable_if<std::is_array<T>::value, std::size_t>::type
  198. {
  199. return sizeof(T) / sizeof(typename std::remove_all_extents<T>::type);
  200. }
  201. template <class T, std::size_t N>
  202. constexpr auto detect_fields_count_dispatch(size_t_<N>, long, int) noexcept
  203. -> decltype(sizeof(T{}))
  204. {
  205. constexpr std::size_t middle = N / 2 + 1;
  206. return detail::detect_fields_count<T, 0, middle>(detail::multi_element_range{}, 1L);
  207. }
  208. template <class T, std::size_t N>
  209. constexpr std::size_t detect_fields_count_dispatch(size_t_<N>, int, int) noexcept {
  210. // T is not default aggregate initialzable. It means that at least one of the members is not default constructible,
  211. // so we have to check all the aggregate initializations for T up to N parameters and return the bigest succeeded
  212. // (we can not use binary search for detecting fields count).
  213. return detail::detect_fields_count_greedy<T, 0, N>(detail::multi_element_range{});
  214. }
  215. ///////////////////// Returns fields count
  216. template <class T>
  217. constexpr std::size_t fields_count() noexcept {
  218. using type = std::remove_cv_t<T>;
  219. static_assert(
  220. !std::is_reference<type>::value,
  221. "====================> 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."
  222. );
  223. #if !BOOST_PFR_HAS_GUARANTEED_COPY_ELISION
  224. static_assert(
  225. std::is_copy_constructible<std::remove_all_extents_t<type>>::value || (
  226. std::is_move_constructible<std::remove_all_extents_t<type>>::value
  227. && std::is_move_assignable<std::remove_all_extents_t<type>>::value
  228. ),
  229. "====================> Boost.PFR: Type and each field in the type must be copy constructible (or move constructible and move assignable)."
  230. );
  231. #endif // #if !BOOST_PFR_HAS_GUARANTEED_COPY_ELISION
  232. static_assert(
  233. !std::is_polymorphic<type>::value,
  234. "====================> Boost.PFR: Type must have no virtual function, because otherwise it is not aggregate initializable."
  235. );
  236. #ifdef __cpp_lib_is_aggregate
  237. static_assert(
  238. std::is_aggregate<type>::value // Does not return `true` for built-in types.
  239. || std::is_scalar<type>::value,
  240. "====================> Boost.PFR: Type must be aggregate initializable."
  241. );
  242. #endif
  243. // Can't use the following. See the non_std_layout.cpp test.
  244. //#if !BOOST_PFR_USE_CPP17
  245. // static_assert(
  246. // std::is_standard_layout<type>::value, // Does not return `true` for structs that have non standard layout members.
  247. // "Type must be aggregate initializable."
  248. // );
  249. //#endif
  250. #if defined(_MSC_VER) && (_MSC_VER <= 1920)
  251. // Workaround for msvc compilers. Versions <= 1920 have a limit of max 1024 elements in template parameter pack
  252. constexpr std::size_t max_fields_count = (sizeof(type) * CHAR_BIT >= 1024 ? 1024 : sizeof(type) * CHAR_BIT);
  253. #else
  254. constexpr std::size_t max_fields_count = (sizeof(type) * CHAR_BIT); // We multiply by CHAR_BIT because the type may have bitfields in T
  255. #endif
  256. constexpr std::size_t result = detail::detect_fields_count_dispatch<type>(size_t_<max_fields_count>{}, 1L, 1L);
  257. detail::assert_first_not_base<type>(detail::make_index_sequence<result>{});
  258. #ifndef __cpp_lib_is_aggregate
  259. static_assert(
  260. is_aggregate_initializable_n<type, result>::value,
  261. "====================> Boost.PFR: Types with user specified constructors (non-aggregate initializable types) are not supported."
  262. );
  263. #endif
  264. static_assert(
  265. result != 0 || std::is_empty<type>::value || std::is_fundamental<type>::value || std::is_reference<type>::value,
  266. "====================> 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."
  267. );
  268. return result;
  269. }
  270. }}} // namespace boost::pfr::detail
  271. #ifdef __clang__
  272. # pragma clang diagnostic pop
  273. #endif
  274. #endif // BOOST_PFR_DETAIL_FIELDS_COUNT_HPP