variant.h 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634
  1. // Copyright 2017 The Abseil Authors.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. //
  15. // Implementation details of absl/types/variant.h, pulled into a
  16. // separate file to avoid cluttering the top of the API header with
  17. // implementation details.
  18. #ifndef ABSL_TYPES_variant_internal_H_
  19. #define ABSL_TYPES_variant_internal_H_
  20. #include <cassert>
  21. #include <cstddef>
  22. #include <cstdlib>
  23. #include <memory>
  24. #include <stdexcept>
  25. #include <tuple>
  26. #include <type_traits>
  27. #include "absl/base/config.h"
  28. #include "absl/base/internal/identity.h"
  29. #include "absl/base/internal/inline_variable.h"
  30. #include "absl/base/internal/invoke.h"
  31. #include "absl/base/macros.h"
  32. #include "absl/base/optimization.h"
  33. #include "absl/meta/type_traits.h"
  34. #include "absl/types/bad_variant_access.h"
  35. #include "absl/utility/utility.h"
  36. namespace absl {
  37. inline namespace lts_2018_06_20 {
  38. template <class... Types>
  39. class variant;
  40. ABSL_INTERNAL_INLINE_CONSTEXPR(size_t, variant_npos, -1);
  41. template <class T>
  42. struct variant_size;
  43. template <std::size_t I, class T>
  44. struct variant_alternative;
  45. namespace variant_internal {
  46. // NOTE: See specializations below for details.
  47. template <std::size_t I, class T>
  48. struct VariantAlternativeSfinae {};
  49. // Requires: I < variant_size_v<T>.
  50. //
  51. // Value: The Ith type of Types...
  52. template <std::size_t I, class T0, class... Tn>
  53. struct VariantAlternativeSfinae<I, variant<T0, Tn...>>
  54. : VariantAlternativeSfinae<I - 1, variant<Tn...>> {};
  55. // Value: T0
  56. template <class T0, class... Ts>
  57. struct VariantAlternativeSfinae<0, variant<T0, Ts...>> {
  58. using type = T0;
  59. };
  60. template <std::size_t I, class T>
  61. using VariantAlternativeSfinaeT = typename VariantAlternativeSfinae<I, T>::type;
  62. // NOTE: Requires T to be a reference type.
  63. template <class T, class U>
  64. struct GiveQualsTo;
  65. template <class T, class U>
  66. struct GiveQualsTo<T&, U> {
  67. using type = U&;
  68. };
  69. template <class T, class U>
  70. struct GiveQualsTo<T&&, U> {
  71. using type = U&&;
  72. };
  73. template <class T, class U>
  74. struct GiveQualsTo<const T&, U> {
  75. using type = const U&;
  76. };
  77. template <class T, class U>
  78. struct GiveQualsTo<const T&&, U> {
  79. using type = const U&&;
  80. };
  81. template <class T, class U>
  82. struct GiveQualsTo<volatile T&, U> {
  83. using type = volatile U&;
  84. };
  85. template <class T, class U>
  86. struct GiveQualsTo<volatile T&&, U> {
  87. using type = volatile U&&;
  88. };
  89. template <class T, class U>
  90. struct GiveQualsTo<volatile const T&, U> {
  91. using type = volatile const U&;
  92. };
  93. template <class T, class U>
  94. struct GiveQualsTo<volatile const T&&, U> {
  95. using type = volatile const U&&;
  96. };
  97. template <class T, class U>
  98. using GiveQualsToT = typename GiveQualsTo<T, U>::type;
  99. // Convenience alias, since size_t integral_constant is used a lot in this file.
  100. template <std::size_t I>
  101. using SizeT = std::integral_constant<std::size_t, I>;
  102. using NPos = SizeT<variant_npos>;
  103. template <class Variant, class T, class = void>
  104. struct IndexOfConstructedType {};
  105. template <std::size_t I, class Variant>
  106. struct VariantAccessResultImpl;
  107. template <std::size_t I, template <class...> class Variantemplate, class... T>
  108. struct VariantAccessResultImpl<I, Variantemplate<T...>&> {
  109. using type = typename absl::variant_alternative<I, variant<T...>>::type&;
  110. };
  111. template <std::size_t I, template <class...> class Variantemplate, class... T>
  112. struct VariantAccessResultImpl<I, const Variantemplate<T...>&> {
  113. using type =
  114. const typename absl::variant_alternative<I, variant<T...>>::type&;
  115. };
  116. template <std::size_t I, template <class...> class Variantemplate, class... T>
  117. struct VariantAccessResultImpl<I, Variantemplate<T...>&&> {
  118. using type = typename absl::variant_alternative<I, variant<T...>>::type&&;
  119. };
  120. template <std::size_t I, template <class...> class Variantemplate, class... T>
  121. struct VariantAccessResultImpl<I, const Variantemplate<T...>&&> {
  122. using type =
  123. const typename absl::variant_alternative<I, variant<T...>>::type&&;
  124. };
  125. template <std::size_t I, class Variant>
  126. using VariantAccessResult =
  127. typename VariantAccessResultImpl<I, Variant&&>::type;
  128. // NOTE: This is used instead of std::array to reduce instantiation overhead.
  129. template <class T, std::size_t Size>
  130. struct SimpleArray {
  131. static_assert(Size != 0, "");
  132. T value[Size];
  133. };
  134. template <class T>
  135. struct AccessedType {
  136. using type = T;
  137. };
  138. template <class T>
  139. using AccessedTypeT = typename AccessedType<T>::type;
  140. template <class T, std::size_t Size>
  141. struct AccessedType<SimpleArray<T, Size>> {
  142. using type = AccessedTypeT<T>;
  143. };
  144. template <class T>
  145. constexpr T AccessSimpleArray(const T& value) {
  146. return value;
  147. }
  148. template <class T, std::size_t Size, class... SizeT>
  149. constexpr AccessedTypeT<T> AccessSimpleArray(const SimpleArray<T, Size>& table,
  150. std::size_t head_index,
  151. SizeT... tail_indices) {
  152. return AccessSimpleArray(table.value[head_index], tail_indices...);
  153. }
  154. // Note: Intentionally is an alias.
  155. template <class T>
  156. using AlwaysZero = SizeT<0>;
  157. template <class Op, class... Vs>
  158. struct VisitIndicesResultImpl {
  159. using type = absl::result_of_t<Op(AlwaysZero<Vs>...)>;
  160. };
  161. template <class Op, class... Vs>
  162. using VisitIndicesResultT = typename VisitIndicesResultImpl<Op, Vs...>::type;
  163. template <class ReturnType, class FunctionObject, class EndIndices,
  164. std::size_t... BoundIndices>
  165. struct MakeVisitationMatrix;
  166. template <class ReturnType, class FunctionObject, std::size_t... Indices>
  167. constexpr ReturnType call_with_indices(FunctionObject&& function) {
  168. static_assert(
  169. std::is_same<ReturnType, decltype(std::declval<FunctionObject>()(
  170. SizeT<Indices>()...))>::value,
  171. "Not all visitation overloads have the same return type.");
  172. return absl::forward<FunctionObject>(function)(SizeT<Indices>()...);
  173. }
  174. template <class ReturnType, class FunctionObject, std::size_t... BoundIndices>
  175. struct MakeVisitationMatrix<ReturnType, FunctionObject, index_sequence<>,
  176. BoundIndices...> {
  177. using ResultType = ReturnType (*)(FunctionObject&&);
  178. static constexpr ResultType Run() {
  179. return &call_with_indices<ReturnType, FunctionObject,
  180. (BoundIndices - 1)...>;
  181. }
  182. };
  183. template <class ReturnType, class FunctionObject, class EndIndices,
  184. class CurrIndices, std::size_t... BoundIndices>
  185. struct MakeVisitationMatrixImpl;
  186. template <class ReturnType, class FunctionObject, std::size_t... EndIndices,
  187. std::size_t... CurrIndices, std::size_t... BoundIndices>
  188. struct MakeVisitationMatrixImpl<
  189. ReturnType, FunctionObject, index_sequence<EndIndices...>,
  190. index_sequence<CurrIndices...>, BoundIndices...> {
  191. using ResultType = SimpleArray<
  192. typename MakeVisitationMatrix<ReturnType, FunctionObject,
  193. index_sequence<EndIndices...>>::ResultType,
  194. sizeof...(CurrIndices)>;
  195. static constexpr ResultType Run() {
  196. return {{MakeVisitationMatrix<ReturnType, FunctionObject,
  197. index_sequence<EndIndices...>,
  198. BoundIndices..., CurrIndices>::Run()...}};
  199. }
  200. };
  201. template <class ReturnType, class FunctionObject, std::size_t HeadEndIndex,
  202. std::size_t... TailEndIndices, std::size_t... BoundIndices>
  203. struct MakeVisitationMatrix<ReturnType, FunctionObject,
  204. index_sequence<HeadEndIndex, TailEndIndices...>,
  205. BoundIndices...>
  206. : MakeVisitationMatrixImpl<
  207. ReturnType, FunctionObject, index_sequence<TailEndIndices...>,
  208. absl::make_index_sequence<HeadEndIndex>, BoundIndices...> {};
  209. struct UnreachableSwitchCase {
  210. template <class Op>
  211. [[noreturn]] static VisitIndicesResultT<Op, std::size_t> Run(
  212. Op&& /*ignored*/) {
  213. #if ABSL_HAVE_BUILTIN(__builtin_unreachable) || \
  214. (defined(__GNUC__) && !defined(__clang__))
  215. __builtin_unreachable();
  216. #elif defined(_MSC_VER)
  217. __assume(false);
  218. #else
  219. // Try to use assert of false being identified as an unreachable intrinsic.
  220. // NOTE: We use assert directly to increase chances of exploiting an assume
  221. // intrinsic.
  222. assert(false); // NOLINT
  223. // Hack to silence potential no return warning -- cause an infinite loop.
  224. return Run(absl::forward<Op>(op));
  225. #endif // Checks for __builtin_unreachable
  226. }
  227. };
  228. template <class Op, std::size_t I>
  229. struct ReachableSwitchCase {
  230. static VisitIndicesResultT<Op, std::size_t> Run(Op&& op) {
  231. return absl::base_internal::Invoke(absl::forward<Op>(op), SizeT<I>());
  232. }
  233. };
  234. // The number 33 is just a guess at a reasonable maximum to our switch. It is
  235. // not based on any analysis. The reason it is a power of 2 plus 1 instead of a
  236. // power of 2 is because the number was picked to correspond to a power of 2
  237. // amount of "normal" alternatives, plus one for the possibility of the user
  238. // providing "monostate" in addition to the more natural alternatives.
  239. ABSL_INTERNAL_INLINE_CONSTEXPR(std::size_t, MaxUnrolledVisitCases, 33);
  240. // Note: The default-definition is for unreachable cases.
  241. template <bool IsReachable>
  242. struct PickCaseImpl {
  243. template <class Op, std::size_t I>
  244. using Apply = UnreachableSwitchCase;
  245. };
  246. template <>
  247. struct PickCaseImpl</*IsReachable =*/true> {
  248. template <class Op, std::size_t I>
  249. using Apply = ReachableSwitchCase<Op, I>;
  250. };
  251. // Note: This form of dance with template aliases is to make sure that we
  252. // instantiate a number of templates proportional to the number of variant
  253. // alternatives rather than a number of templates proportional to our
  254. // maximum unrolled amount of visitation cases (aliases are effectively
  255. // "free" whereas other template instantiations are costly).
  256. template <class Op, std::size_t I, std::size_t EndIndex>
  257. using PickCase = typename PickCaseImpl<(I < EndIndex)>::template Apply<Op, I>;
  258. template <class ReturnType>
  259. [[noreturn]] ReturnType TypedThrowBadVariantAccess() {
  260. absl::variant_internal::ThrowBadVariantAccess();
  261. }
  262. // Given N variant sizes, determine the number of cases there would need to be
  263. // in a single switch-statement that would cover every possibility in the
  264. // corresponding N-ary visit operation.
  265. template <std::size_t... NumAlternatives>
  266. struct NumCasesOfSwitch;
  267. template <std::size_t HeadNumAlternatives, std::size_t... TailNumAlternatives>
  268. struct NumCasesOfSwitch<HeadNumAlternatives, TailNumAlternatives...> {
  269. static constexpr std::size_t value =
  270. (HeadNumAlternatives + 1) *
  271. NumCasesOfSwitch<TailNumAlternatives...>::value;
  272. };
  273. template <>
  274. struct NumCasesOfSwitch<> {
  275. static constexpr std::size_t value = 1;
  276. };
  277. // A switch statement optimizes better than the table of function pointers.
  278. template <std::size_t EndIndex>
  279. struct VisitIndicesSwitch {
  280. static_assert(EndIndex <= MaxUnrolledVisitCases,
  281. "Maximum unrolled switch size exceeded.");
  282. template <class Op>
  283. static VisitIndicesResultT<Op, std::size_t> Run(Op&& op, std::size_t i) {
  284. switch (i) {
  285. case 0:
  286. return PickCase<Op, 0, EndIndex>::Run(absl::forward<Op>(op));
  287. case 1:
  288. return PickCase<Op, 1, EndIndex>::Run(absl::forward<Op>(op));
  289. case 2:
  290. return PickCase<Op, 2, EndIndex>::Run(absl::forward<Op>(op));
  291. case 3:
  292. return PickCase<Op, 3, EndIndex>::Run(absl::forward<Op>(op));
  293. case 4:
  294. return PickCase<Op, 4, EndIndex>::Run(absl::forward<Op>(op));
  295. case 5:
  296. return PickCase<Op, 5, EndIndex>::Run(absl::forward<Op>(op));
  297. case 6:
  298. return PickCase<Op, 6, EndIndex>::Run(absl::forward<Op>(op));
  299. case 7:
  300. return PickCase<Op, 7, EndIndex>::Run(absl::forward<Op>(op));
  301. case 8:
  302. return PickCase<Op, 8, EndIndex>::Run(absl::forward<Op>(op));
  303. case 9:
  304. return PickCase<Op, 9, EndIndex>::Run(absl::forward<Op>(op));
  305. case 10:
  306. return PickCase<Op, 10, EndIndex>::Run(absl::forward<Op>(op));
  307. case 11:
  308. return PickCase<Op, 11, EndIndex>::Run(absl::forward<Op>(op));
  309. case 12:
  310. return PickCase<Op, 12, EndIndex>::Run(absl::forward<Op>(op));
  311. case 13:
  312. return PickCase<Op, 13, EndIndex>::Run(absl::forward<Op>(op));
  313. case 14:
  314. return PickCase<Op, 14, EndIndex>::Run(absl::forward<Op>(op));
  315. case 15:
  316. return PickCase<Op, 15, EndIndex>::Run(absl::forward<Op>(op));
  317. case 16:
  318. return PickCase<Op, 16, EndIndex>::Run(absl::forward<Op>(op));
  319. case 17:
  320. return PickCase<Op, 17, EndIndex>::Run(absl::forward<Op>(op));
  321. case 18:
  322. return PickCase<Op, 18, EndIndex>::Run(absl::forward<Op>(op));
  323. case 19:
  324. return PickCase<Op, 19, EndIndex>::Run(absl::forward<Op>(op));
  325. case 20:
  326. return PickCase<Op, 20, EndIndex>::Run(absl::forward<Op>(op));
  327. case 21:
  328. return PickCase<Op, 21, EndIndex>::Run(absl::forward<Op>(op));
  329. case 22:
  330. return PickCase<Op, 22, EndIndex>::Run(absl::forward<Op>(op));
  331. case 23:
  332. return PickCase<Op, 23, EndIndex>::Run(absl::forward<Op>(op));
  333. case 24:
  334. return PickCase<Op, 24, EndIndex>::Run(absl::forward<Op>(op));
  335. case 25:
  336. return PickCase<Op, 25, EndIndex>::Run(absl::forward<Op>(op));
  337. case 26:
  338. return PickCase<Op, 26, EndIndex>::Run(absl::forward<Op>(op));
  339. case 27:
  340. return PickCase<Op, 27, EndIndex>::Run(absl::forward<Op>(op));
  341. case 28:
  342. return PickCase<Op, 28, EndIndex>::Run(absl::forward<Op>(op));
  343. case 29:
  344. return PickCase<Op, 29, EndIndex>::Run(absl::forward<Op>(op));
  345. case 30:
  346. return PickCase<Op, 30, EndIndex>::Run(absl::forward<Op>(op));
  347. case 31:
  348. return PickCase<Op, 31, EndIndex>::Run(absl::forward<Op>(op));
  349. case 32:
  350. return PickCase<Op, 32, EndIndex>::Run(absl::forward<Op>(op));
  351. default:
  352. ABSL_ASSERT(i == variant_npos);
  353. return absl::base_internal::Invoke(absl::forward<Op>(op), NPos());
  354. }
  355. }
  356. };
  357. template <std::size_t... EndIndices>
  358. struct VisitIndicesFallback {
  359. template <class Op, class... SizeT>
  360. static VisitIndicesResultT<Op, SizeT...> Run(Op&& op, SizeT... indices) {
  361. return AccessSimpleArray(
  362. MakeVisitationMatrix<VisitIndicesResultT<Op, SizeT...>, Op,
  363. index_sequence<(EndIndices + 1)...>>::Run(),
  364. (indices + 1)...)(absl::forward<Op>(op));
  365. }
  366. };
  367. // Take an N-dimensional series of indices and convert them into a single index
  368. // without loss of information. The purpose of this is to be able to convert an
  369. // N-ary visit operation into a single switch statement.
  370. template <std::size_t...>
  371. struct FlattenIndices;
  372. template <std::size_t HeadSize, std::size_t... TailSize>
  373. struct FlattenIndices<HeadSize, TailSize...> {
  374. template<class... SizeType>
  375. static constexpr std::size_t Run(std::size_t head, SizeType... tail) {
  376. return head + HeadSize * FlattenIndices<TailSize...>::Run(tail...);
  377. }
  378. };
  379. template <>
  380. struct FlattenIndices<> {
  381. static constexpr std::size_t Run() { return 0; }
  382. };
  383. // Take a single "flattened" index (flattened by FlattenIndices) and determine
  384. // the value of the index of one of the logically represented dimensions.
  385. template <std::size_t I, std::size_t IndexToGet, std::size_t HeadSize,
  386. std::size_t... TailSize>
  387. struct UnflattenIndex {
  388. static constexpr std::size_t value =
  389. UnflattenIndex<I / HeadSize, IndexToGet - 1, TailSize...>::value;
  390. };
  391. template <std::size_t I, std::size_t HeadSize, std::size_t... TailSize>
  392. struct UnflattenIndex<I, 0, HeadSize, TailSize...> {
  393. static constexpr std::size_t value = (I % HeadSize);
  394. };
  395. // The backend for converting an N-ary visit operation into a unary visit.
  396. template <class IndexSequence, std::size_t... EndIndices>
  397. struct VisitIndicesVariadicImpl;
  398. template <std::size_t... N, std::size_t... EndIndices>
  399. struct VisitIndicesVariadicImpl<absl::index_sequence<N...>, EndIndices...> {
  400. // A type that can take an N-ary function object and converts it to a unary
  401. // function object that takes a single, flattened index, and "unflattens" it
  402. // into its individual dimensions when forwarding to the wrapped object.
  403. template <class Op>
  404. struct FlattenedOp {
  405. template <std::size_t I>
  406. VisitIndicesResultT<Op, decltype(EndIndices)...> operator()(
  407. SizeT<I> /*index*/) && {
  408. return base_internal::Invoke(
  409. absl::forward<Op>(op),
  410. SizeT<UnflattenIndex<I, N, (EndIndices + 1)...>::value -
  411. std::size_t{1}>()...);
  412. }
  413. Op&& op;
  414. };
  415. template <class Op, class... SizeType>
  416. static VisitIndicesResultT<Op, decltype(EndIndices)...> Run(
  417. Op&& op, SizeType... i) {
  418. return VisitIndicesSwitch<NumCasesOfSwitch<EndIndices...>::value>::Run(
  419. FlattenedOp<Op>{absl::forward<Op>(op)},
  420. FlattenIndices<(EndIndices + std::size_t{1})...>::Run(
  421. (i + std::size_t{1})...));
  422. }
  423. };
  424. template <std::size_t... EndIndices>
  425. struct VisitIndicesVariadic
  426. : VisitIndicesVariadicImpl<absl::make_index_sequence<sizeof...(EndIndices)>,
  427. EndIndices...> {};
  428. // This implementation will flatten N-ary visit operations into a single switch
  429. // statement when the number of cases would be less than our maximum specified
  430. // switch-statement size.
  431. // TODO(calabrese)
  432. // Based on benchmarks, determine whether the function table approach actually
  433. // does optimize better than a chain of switch statements and possibly update
  434. // the implementation accordingly. Also consider increasing the maximum switch
  435. // size.
  436. template <std::size_t... EndIndices>
  437. struct VisitIndices
  438. : absl::conditional_t<(NumCasesOfSwitch<EndIndices...>::value <=
  439. MaxUnrolledVisitCases),
  440. VisitIndicesVariadic<EndIndices...>,
  441. VisitIndicesFallback<EndIndices...>> {};
  442. template <std::size_t EndIndex>
  443. struct VisitIndices<EndIndex>
  444. : absl::conditional_t<(EndIndex <= MaxUnrolledVisitCases),
  445. VisitIndicesSwitch<EndIndex>,
  446. VisitIndicesFallback<EndIndex>> {};
  447. // Suppress bogus warning on MSVC: MSVC complains that the `reinterpret_cast`
  448. // below is returning the address of a temporary or local object.
  449. #ifdef _MSC_VER
  450. #pragma warning(push)
  451. #pragma warning(disable : 4172)
  452. #endif // _MSC_VER
  453. // TODO(calabrese) std::launder
  454. // TODO(calabrese) constexpr
  455. // NOTE: DO NOT REMOVE the `inline` keyword as it is necessary to work around a
  456. // MSVC bug. See https://github.com/abseil/abseil-cpp/issues/129 for details.
  457. template <class Self, std::size_t I>
  458. inline VariantAccessResult<I, Self> AccessUnion(Self&& self, SizeT<I> /*i*/) {
  459. return reinterpret_cast<VariantAccessResult<I, Self>>(self);
  460. }
  461. #ifdef _MSC_VER
  462. #pragma warning(pop)
  463. #endif // _MSC_VER
  464. template <class T>
  465. void DeducedDestroy(T& self) { // NOLINT
  466. self.~T();
  467. }
  468. // NOTE: This type exists as a single entity for variant and its bases to
  469. // befriend. It contains helper functionality that manipulates the state of the
  470. // variant, such as the implementation of things like assignment and emplace
  471. // operations.
  472. struct VariantCoreAccess {
  473. template <class VariantType>
  474. static typename VariantType::Variant& Derived(VariantType& self) { // NOLINT
  475. return static_cast<typename VariantType::Variant&>(self);
  476. }
  477. template <class VariantType>
  478. static const typename VariantType::Variant& Derived(
  479. const VariantType& self) { // NOLINT
  480. return static_cast<const typename VariantType::Variant&>(self);
  481. }
  482. template <class VariantType>
  483. static void Destroy(VariantType& self) { // NOLINT
  484. Derived(self).destroy();
  485. self.index_ = absl::variant_npos;
  486. }
  487. template <class Variant>
  488. static void SetIndex(Variant& self, std::size_t i) { // NOLINT
  489. self.index_ = i;
  490. }
  491. template <class Variant>
  492. static void InitFrom(Variant& self, Variant&& other) { // NOLINT
  493. VisitIndices<absl::variant_size<Variant>::value>::Run(
  494. InitFromVisitor<Variant, Variant&&>{&self,
  495. std::forward<Variant>(other)},
  496. other.index());
  497. self.index_ = other.index();
  498. }
  499. template <std::size_t I, class Variant>
  500. static VariantAccessResult<I, Variant> Access(Variant&& self) {
  501. if (ABSL_PREDICT_FALSE(self.index_ != I)) {
  502. TypedThrowBadVariantAccess<VariantAccessResult<I, Variant>>();
  503. }
  504. // This cast instead of invocation of AccessUnion with an rvalue is a
  505. // workaround for msvc. Without this there is a runtime failure when dealing
  506. // with rvalues.
  507. // TODO(calabrese) Reduce test case and find a simpler workaround.
  508. return static_cast<VariantAccessResult<I, Variant>>(
  509. variant_internal::AccessUnion(self.state_, SizeT<I>()));
  510. }
  511. // The implementation of the move-assignment operation for a variant.
  512. template <class VType>
  513. struct MoveAssignVisitor {
  514. using DerivedType = typename VType::Variant;
  515. template <std::size_t NewIndex>
  516. void operator()(SizeT<NewIndex> /*new_i*/) const {
  517. if (left->index_ == NewIndex) {
  518. Access<NewIndex>(*left) = std::move(Access<NewIndex>(*right));
  519. } else {
  520. Derived(*left).template emplace<NewIndex>(
  521. std::move(Access<NewIndex>(*right)));
  522. }
  523. }
  524. void operator()(SizeT<absl::variant_npos> /*new_i*/) const {
  525. Destroy(*left);
  526. }
  527. VType* left;
  528. VType* right;
  529. };
  530. template <class VType>
  531. static MoveAssignVisitor<VType> MakeMoveAssignVisitor(VType* left,
  532. VType* other) {
  533. return {left, other};
  534. }
  535. // The implementation of the assignment operation for a variant.
  536. template <class VType>
  537. struct CopyAssignVisitor {
  538. using DerivedType = typename VType::Variant;
  539. template <std::size_t NewIndex>
  540. void operator()(SizeT<NewIndex> /*new_i*/) const {
  541. using New =
  542. typename absl::variant_alternative<NewIndex, DerivedType>::type;
  543. if (left->index_ == NewIndex) {
  544. Access<NewIndex>(*left) = Access<NewIndex>(*right);
  545. } else if (std::is_nothrow_copy_constructible<New>::value ||
  546. !std::is_nothrow_move_constructible<New>::value) {
  547. Derived(*left).template emplace<NewIndex>(Access<NewIndex>(*right));
  548. } else {
  549. Derived(*left) = DerivedType(Derived(*right));
  550. }
  551. }
  552. void operator()(SizeT<absl::variant_npos> /*new_i*/) const {
  553. Destroy(*left);
  554. }
  555. VType* left;
  556. const VType* right;
  557. };
  558. template <class VType>
  559. static CopyAssignVisitor<VType> MakeCopyAssignVisitor(VType* left,
  560. const VType& other) {
  561. return {left, &other};
  562. }
  563. // The implementation of conversion-assignment operations for variant.
  564. template <class Left, class QualifiedNew>
  565. struct ConversionAssignVisitor {
  566. using NewIndex =
  567. variant_internal::IndexOfConstructedType<Left, QualifiedNew>;
  568. void operator()(SizeT<NewIndex::value> /*old_i*/
  569. ) const {
  570. Access<NewIndex::value>(*left) = absl::forward<QualifiedNew>(other);
  571. }
  572. template <std::size_t OldIndex>
  573. void operator()(SizeT<OldIndex> /*old_i*/
  574. ) const {
  575. using New =
  576. typename absl::variant_alternative<NewIndex::value, Left>::type;
  577. if (std::is_nothrow_constructible<New, QualifiedNew>::value ||
  578. !std::is_nothrow_move_constructible<New>::value) {
  579. left->template emplace<NewIndex::value>(
  580. absl::forward<QualifiedNew>(other));
  581. } else {
  582. // the standard says "equivalent to
  583. // operator=(variant(std::forward<T>(t)))", but we use `emplace` here
  584. // because the variant's move assignment operator could be deleted.
  585. left->template emplace<NewIndex::value>(
  586. New(absl::forward<QualifiedNew>(other)));
  587. }
  588. }
  589. Left* left;
  590. QualifiedNew&& other;
  591. };
  592. template <class Left, class QualifiedNew>
  593. static ConversionAssignVisitor<Left, QualifiedNew>
  594. MakeConversionAssignVisitor(Left* left, QualifiedNew&& qual) {
  595. return {left, absl::forward<QualifiedNew>(qual)};
  596. }
  597. // Backend for operations for `emplace()` which destructs `*self` then
  598. // construct a new alternative with `Args...`.
  599. template <std::size_t NewIndex, class Self, class... Args>
  600. static typename absl::variant_alternative<NewIndex, Self>::type& Replace(
  601. Self* self, Args&&... args) {
  602. Destroy(*self);
  603. using New = typename absl::variant_alternative<NewIndex, Self>::type;
  604. New* const result = ::new (static_cast<void*>(&self->state_))
  605. New(absl::forward<Args>(args)...);
  606. self->index_ = NewIndex;
  607. return *result;
  608. }
  609. template <class LeftVariant, class QualifiedRightVariant>
  610. struct InitFromVisitor {
  611. template <std::size_t NewIndex>
  612. void operator()(SizeT<NewIndex> /*new_i*/) const {
  613. using Alternative =
  614. typename variant_alternative<NewIndex, LeftVariant>::type;
  615. ::new (static_cast<void*>(&left->state_)) Alternative(
  616. Access<NewIndex>(std::forward<QualifiedRightVariant>(right)));
  617. }
  618. void operator()(SizeT<absl::variant_npos> /*new_i*/) const {
  619. // This space intentionally left blank.
  620. }
  621. LeftVariant* left;
  622. QualifiedRightVariant&& right;
  623. };
  624. };
  625. template <class Expected, class... T>
  626. struct IndexOfImpl;
  627. template <class Expected>
  628. struct IndexOfImpl<Expected> {
  629. using IndexFromEnd = SizeT<0>;
  630. using MatchedIndexFromEnd = IndexFromEnd;
  631. using MultipleMatches = std::false_type;
  632. };
  633. template <class Expected, class Head, class... Tail>
  634. struct IndexOfImpl<Expected, Head, Tail...> : IndexOfImpl<Expected, Tail...> {
  635. using IndexFromEnd =
  636. SizeT<IndexOfImpl<Expected, Tail...>::IndexFromEnd::value + 1>;
  637. };
  638. template <class Expected, class... Tail>
  639. struct IndexOfImpl<Expected, Expected, Tail...>
  640. : IndexOfImpl<Expected, Tail...> {
  641. using IndexFromEnd =
  642. SizeT<IndexOfImpl<Expected, Tail...>::IndexFromEnd::value + 1>;
  643. using MatchedIndexFromEnd = IndexFromEnd;
  644. using MultipleMatches = std::integral_constant<
  645. bool, IndexOfImpl<Expected, Tail...>::MatchedIndexFromEnd::value != 0>;
  646. };
  647. template <class Expected, class... Types>
  648. struct IndexOfMeta {
  649. using Results = IndexOfImpl<Expected, Types...>;
  650. static_assert(!Results::MultipleMatches::value,
  651. "Attempted to access a variant by specifying a type that "
  652. "matches more than one alternative.");
  653. static_assert(Results::MatchedIndexFromEnd::value != 0,
  654. "Attempted to access a variant by specifying a type that does "
  655. "not match any alternative.");
  656. using type = SizeT<sizeof...(Types) - Results::MatchedIndexFromEnd::value>;
  657. };
  658. template <class Expected, class... Types>
  659. using IndexOf = typename IndexOfMeta<Expected, Types...>::type;
  660. template <class Variant, class T, std::size_t CurrIndex>
  661. struct UnambiguousIndexOfImpl;
  662. // Terminating case encountered once we've checked all of the alternatives
  663. template <class T, std::size_t CurrIndex>
  664. struct UnambiguousIndexOfImpl<variant<>, T, CurrIndex> : SizeT<CurrIndex> {};
  665. // Case where T is not Head
  666. template <class Head, class... Tail, class T, std::size_t CurrIndex>
  667. struct UnambiguousIndexOfImpl<variant<Head, Tail...>, T, CurrIndex>
  668. : UnambiguousIndexOfImpl<variant<Tail...>, T, CurrIndex + 1>::type {};
  669. // Case where T is Head
  670. template <class Head, class... Tail, std::size_t CurrIndex>
  671. struct UnambiguousIndexOfImpl<variant<Head, Tail...>, Head, CurrIndex>
  672. : SizeT<UnambiguousIndexOfImpl<variant<Tail...>, Head, 0>::value ==
  673. sizeof...(Tail)
  674. ? CurrIndex
  675. : CurrIndex + sizeof...(Tail) + 1> {};
  676. template <class Variant, class T>
  677. struct UnambiguousIndexOf;
  678. struct NoMatch {
  679. struct type {};
  680. };
  681. template <class... Alts, class T>
  682. struct UnambiguousIndexOf<variant<Alts...>, T>
  683. : std::conditional<UnambiguousIndexOfImpl<variant<Alts...>, T, 0>::value !=
  684. sizeof...(Alts),
  685. UnambiguousIndexOfImpl<variant<Alts...>, T, 0>,
  686. NoMatch>::type::type {};
  687. template <class T, std::size_t /*Dummy*/>
  688. using UnambiguousTypeOfImpl = T;
  689. template <class Variant, class T>
  690. using UnambiguousTypeOfT =
  691. UnambiguousTypeOfImpl<T, UnambiguousIndexOf<Variant, T>::value>;
  692. template <class H, class... T>
  693. class VariantStateBase;
  694. // This is an implementation of the "imaginary function" that is described in
  695. // [variant.ctor]
  696. // It is used in order to determine which alternative to construct during
  697. // initialization from some type T.
  698. template <class Variant, std::size_t I = 0>
  699. struct ImaginaryFun;
  700. template <std::size_t I>
  701. struct ImaginaryFun<variant<>, I> {
  702. static void Run() = delete;
  703. };
  704. template <class H, class... T, std::size_t I>
  705. struct ImaginaryFun<variant<H, T...>, I> : ImaginaryFun<variant<T...>, I + 1> {
  706. using ImaginaryFun<variant<T...>, I + 1>::Run;
  707. // NOTE: const& and && are used instead of by-value due to lack of guaranteed
  708. // move elision of C++17. This may have other minor differences, but tests
  709. // pass.
  710. static SizeT<I> Run(const H&);
  711. static SizeT<I> Run(H&&);
  712. };
  713. // The following metafunctions are used in constructor and assignment
  714. // constraints.
  715. template <class Self, class T>
  716. struct IsNeitherSelfNorInPlace : std::true_type {};
  717. template <class Self>
  718. struct IsNeitherSelfNorInPlace<Self, Self> : std::false_type {};
  719. template <class Self, class T>
  720. struct IsNeitherSelfNorInPlace<Self, in_place_type_t<T>> : std::false_type {};
  721. template <class Self, std::size_t I>
  722. struct IsNeitherSelfNorInPlace<Self, in_place_index_t<I>> : std::false_type {};
  723. template <class Variant, class T, class = void>
  724. struct ConversionIsPossibleImpl : std::false_type {};
  725. template <class Variant, class T>
  726. struct ConversionIsPossibleImpl<
  727. Variant, T, void_t<decltype(ImaginaryFun<Variant>::Run(std::declval<T>()))>>
  728. : std::true_type {};
  729. template <class Variant, class T>
  730. struct ConversionIsPossible : ConversionIsPossibleImpl<Variant, T>::type {};
  731. template <class Variant, class T>
  732. struct IndexOfConstructedType<
  733. Variant, T, void_t<decltype(ImaginaryFun<Variant>::Run(std::declval<T>()))>>
  734. : decltype(ImaginaryFun<Variant>::Run(std::declval<T>())) {};
  735. template <std::size_t... Is>
  736. struct ContainsVariantNPos
  737. : absl::negation<std::is_same< // NOLINT
  738. absl::integer_sequence<bool, 0 <= Is...>,
  739. absl::integer_sequence<bool, Is != absl::variant_npos...>>> {};
  740. template <class Op, class... QualifiedVariants>
  741. using RawVisitResult =
  742. absl::result_of_t<Op(VariantAccessResult<0, QualifiedVariants>...)>;
  743. // NOTE: The spec requires that all return-paths yield the same type and is not
  744. // SFINAE-friendly, so we can deduce the return type by examining the first
  745. // result. If it's not callable, then we get an error, but are compliant and
  746. // fast to compile.
  747. // TODO(calabrese) Possibly rewrite in a way that yields better compile errors
  748. // at the cost of longer compile-times.
  749. template <class Op, class... QualifiedVariants>
  750. struct VisitResultImpl {
  751. using type =
  752. absl::result_of_t<Op(VariantAccessResult<0, QualifiedVariants>...)>;
  753. };
  754. // Done in two steps intentionally so that we don't cause substitution to fail.
  755. template <class Op, class... QualifiedVariants>
  756. using VisitResult = typename VisitResultImpl<Op, QualifiedVariants...>::type;
  757. template <class Op, class... QualifiedVariants>
  758. struct PerformVisitation {
  759. using ReturnType = VisitResult<Op, QualifiedVariants...>;
  760. template <std::size_t... Is>
  761. constexpr ReturnType operator()(SizeT<Is>... indices) const {
  762. return Run(typename ContainsVariantNPos<Is...>::type{},
  763. absl::index_sequence_for<QualifiedVariants...>(), indices...);
  764. }
  765. template <std::size_t... TupIs, std::size_t... Is>
  766. constexpr ReturnType Run(std::false_type /*has_valueless*/,
  767. index_sequence<TupIs...>, SizeT<Is>...) const {
  768. return absl::base_internal::Invoke(
  769. absl::forward<Op>(op),
  770. VariantCoreAccess::Access<Is>(
  771. absl::forward<QualifiedVariants>(std::get<TupIs>(variant_tup)))...);
  772. }
  773. template <std::size_t... TupIs, std::size_t... Is>
  774. [[noreturn]] ReturnType Run(std::true_type /*has_valueless*/,
  775. index_sequence<TupIs...>, SizeT<Is>...) const {
  776. absl::variant_internal::ThrowBadVariantAccess();
  777. }
  778. // TODO(calabrese) Avoid using a tuple, which causes lots of instantiations
  779. // Attempts using lambda variadic captures fail on current GCC.
  780. std::tuple<QualifiedVariants&&...> variant_tup;
  781. Op&& op;
  782. };
  783. template <class... T>
  784. union Union;
  785. // We want to allow for variant<> to be trivial. For that, we need the default
  786. // constructor to be trivial, which means we can't define it ourselves.
  787. // Instead, we use a non-default constructor that takes NoopConstructorTag
  788. // that doesn't affect the triviality of the types.
  789. struct NoopConstructorTag {};
  790. template <std::size_t I>
  791. struct EmplaceTag {};
  792. template <>
  793. union Union<> {
  794. constexpr explicit Union(NoopConstructorTag) noexcept {}
  795. };
  796. // Suppress bogus warning on MSVC: MSVC complains that Union<T...> has a defined
  797. // deleted destructor from the `std::is_destructible` check below.
  798. #ifdef _MSC_VER
  799. #pragma warning(push)
  800. #pragma warning(disable : 4624)
  801. #endif // _MSC_VER
  802. template <class Head, class... Tail>
  803. union Union<Head, Tail...> {
  804. using TailUnion = Union<Tail...>;
  805. explicit constexpr Union(NoopConstructorTag /*tag*/) noexcept
  806. : tail(NoopConstructorTag()) {}
  807. template <class... P>
  808. explicit constexpr Union(EmplaceTag<0>, P&&... args)
  809. : head(absl::forward<P>(args)...) {}
  810. template <std::size_t I, class... P>
  811. explicit constexpr Union(EmplaceTag<I>, P&&... args)
  812. : tail(EmplaceTag<I - 1>{}, absl::forward<P>(args)...) {}
  813. Head head;
  814. TailUnion tail;
  815. };
  816. #ifdef _MSC_VER
  817. #pragma warning(pop)
  818. #endif // _MSC_VER
  819. // TODO(calabrese) Just contain a Union in this union (certain configs fail).
  820. template <class... T>
  821. union DestructibleUnionImpl;
  822. template <>
  823. union DestructibleUnionImpl<> {
  824. constexpr explicit DestructibleUnionImpl(NoopConstructorTag) noexcept {}
  825. };
  826. template <class Head, class... Tail>
  827. union DestructibleUnionImpl<Head, Tail...> {
  828. using TailUnion = DestructibleUnionImpl<Tail...>;
  829. explicit constexpr DestructibleUnionImpl(NoopConstructorTag /*tag*/) noexcept
  830. : tail(NoopConstructorTag()) {}
  831. template <class... P>
  832. explicit constexpr DestructibleUnionImpl(EmplaceTag<0>, P&&... args)
  833. : head(absl::forward<P>(args)...) {}
  834. template <std::size_t I, class... P>
  835. explicit constexpr DestructibleUnionImpl(EmplaceTag<I>, P&&... args)
  836. : tail(EmplaceTag<I - 1>{}, absl::forward<P>(args)...) {}
  837. ~DestructibleUnionImpl() {}
  838. Head head;
  839. TailUnion tail;
  840. };
  841. // This union type is destructible even if one or more T are not trivially
  842. // destructible. In the case that all T are trivially destructible, then so is
  843. // this resultant type.
  844. template <class... T>
  845. using DestructibleUnion =
  846. absl::conditional_t<std::is_destructible<Union<T...>>::value, Union<T...>,
  847. DestructibleUnionImpl<T...>>;
  848. // Deepest base, containing the actual union and the discriminator
  849. template <class H, class... T>
  850. class VariantStateBase {
  851. protected:
  852. using Variant = variant<H, T...>;
  853. template <class LazyH = H,
  854. class ConstructibleH = absl::enable_if_t<
  855. std::is_default_constructible<LazyH>::value, LazyH>>
  856. constexpr VariantStateBase() noexcept(
  857. std::is_nothrow_default_constructible<ConstructibleH>::value)
  858. : state_(EmplaceTag<0>()), index_(0) {}
  859. template <std::size_t I, class... P>
  860. explicit constexpr VariantStateBase(EmplaceTag<I> tag, P&&... args)
  861. : state_(tag, absl::forward<P>(args)...), index_(I) {}
  862. explicit constexpr VariantStateBase(NoopConstructorTag)
  863. : state_(NoopConstructorTag()), index_(variant_npos) {}
  864. void destroy() {} // Does nothing (shadowed in child if non-trivial)
  865. DestructibleUnion<H, T...> state_;
  866. std::size_t index_;
  867. };
  868. using absl::internal::identity;
  869. // OverloadSet::Overload() is a unary function which is overloaded to
  870. // take any of the element types of the variant, by reference-to-const.
  871. // The return type of the overload on T is identity<T>, so that you
  872. // can statically determine which overload was called.
  873. //
  874. // Overload() is not defined, so it can only be called in unevaluated
  875. // contexts.
  876. template <typename... Ts>
  877. struct OverloadSet;
  878. template <typename T, typename... Ts>
  879. struct OverloadSet<T, Ts...> : OverloadSet<Ts...> {
  880. using Base = OverloadSet<Ts...>;
  881. static identity<T> Overload(const T&);
  882. using Base::Overload;
  883. };
  884. template <>
  885. struct OverloadSet<> {
  886. // For any case not handled above.
  887. static void Overload(...);
  888. };
  889. ////////////////////////////////
  890. // Library Fundamentals V2 TS //
  891. ////////////////////////////////
  892. // TODO(calabrese): Consider moving this to absl/meta/type_traits.h
  893. // The following is a rough implementation of parts of the detection idiom.
  894. // It is used for the comparison operator checks.
  895. template <class Enabler, class To, template <class...> class Op, class... Args>
  896. struct is_detected_convertible_impl {
  897. using type = std::false_type;
  898. };
  899. template <class To, template <class...> class Op, class... Args>
  900. struct is_detected_convertible_impl<
  901. absl::enable_if_t<std::is_convertible<Op<Args...>, To>::value>, To, Op,
  902. Args...> {
  903. using type = std::true_type;
  904. };
  905. // NOTE: This differs from library fundamentals by being lazy.
  906. template <class To, template <class...> class Op, class... Args>
  907. struct is_detected_convertible
  908. : is_detected_convertible_impl<void, To, Op, Args...>::type {};
  909. template <class T>
  910. using LessThanResult = decltype(std::declval<T>() < std::declval<T>());
  911. template <class T>
  912. using GreaterThanResult = decltype(std::declval<T>() > std::declval<T>());
  913. template <class T>
  914. using LessThanOrEqualResult = decltype(std::declval<T>() <= std::declval<T>());
  915. template <class T>
  916. using GreaterThanOrEqualResult =
  917. decltype(std::declval<T>() >= std::declval<T>());
  918. template <class T>
  919. using EqualResult = decltype(std::declval<T>() == std::declval<T>());
  920. template <class T>
  921. using NotEqualResult = decltype(std::declval<T>() != std::declval<T>());
  922. template <class... T>
  923. using RequireAllHaveEqualT = absl::enable_if_t<
  924. absl::conjunction<is_detected_convertible<bool, EqualResult, T>...>::value,
  925. bool>;
  926. template <class... T>
  927. using RequireAllHaveNotEqualT =
  928. absl::enable_if_t<absl::conjunction<is_detected_convertible<
  929. bool, NotEqualResult, T>...>::value,
  930. bool>;
  931. template <class... T>
  932. using RequireAllHaveLessThanT =
  933. absl::enable_if_t<absl::conjunction<is_detected_convertible<
  934. bool, LessThanResult, T>...>::value,
  935. bool>;
  936. template <class... T>
  937. using RequireAllHaveLessThanOrEqualT =
  938. absl::enable_if_t<absl::conjunction<is_detected_convertible<
  939. bool, LessThanOrEqualResult, T>...>::value,
  940. bool>;
  941. template <class... T>
  942. using RequireAllHaveGreaterThanOrEqualT =
  943. absl::enable_if_t<absl::conjunction<is_detected_convertible<
  944. bool, GreaterThanOrEqualResult, T>...>::value,
  945. bool>;
  946. template <class... T>
  947. using RequireAllHaveGreaterThanT =
  948. absl::enable_if_t<absl::conjunction<is_detected_convertible<
  949. bool, GreaterThanResult, T>...>::value,
  950. bool>;
  951. // Helper template containing implementations details of variant that can't go
  952. // in the private section. For convenience, this takes the variant type as a
  953. // single template parameter.
  954. template <typename T>
  955. struct VariantHelper;
  956. template <typename... Ts>
  957. struct VariantHelper<variant<Ts...>> {
  958. // Type metafunction which returns the element type selected if
  959. // OverloadSet::Overload() is well-formed when called with argument type U.
  960. template <typename U>
  961. using BestMatch = decltype(
  962. variant_internal::OverloadSet<Ts...>::Overload(std::declval<U>()));
  963. // Type metafunction which returns true if OverloadSet::Overload() is
  964. // well-formed when called with argument type U.
  965. // CanAccept can't be just an alias because there is a MSVC bug on parameter
  966. // pack expansion involving decltype.
  967. template <typename U>
  968. struct CanAccept :
  969. std::integral_constant<bool, !std::is_void<BestMatch<U>>::value> {};
  970. // Type metafunction which returns true if Other is an instantiation of
  971. // variant, and variants's converting constructor from Other will be
  972. // well-formed. We will use this to remove constructors that would be
  973. // ill-formed from the overload set.
  974. template <typename Other>
  975. struct CanConvertFrom;
  976. template <typename... Us>
  977. struct CanConvertFrom<variant<Us...>>
  978. : public absl::conjunction<CanAccept<Us>...> {};
  979. };
  980. // A type with nontrivial copy ctor and trivial move ctor.
  981. struct TrivialMoveOnly {
  982. TrivialMoveOnly(TrivialMoveOnly&&) = default;
  983. };
  984. // Trait class to detect whether a type is trivially move constructible.
  985. // A union's defaulted copy/move constructor is deleted if any variant member's
  986. // copy/move constructor is nontrivial.
  987. template <typename T>
  988. struct IsTriviallyMoveConstructible:
  989. std::is_move_constructible<Union<T, TrivialMoveOnly>> {};
  990. // To guarantee triviality of all special-member functions that can be trivial,
  991. // we use a chain of conditional bases for each one.
  992. // The order of inheritance of bases from child to base are logically:
  993. //
  994. // variant
  995. // VariantCopyAssignBase
  996. // VariantMoveAssignBase
  997. // VariantCopyBase
  998. // VariantMoveBase
  999. // VariantStateBaseDestructor
  1000. // VariantStateBase
  1001. //
  1002. // Note that there is a separate branch at each base that is dependent on
  1003. // whether or not that corresponding special-member-function can be trivial in
  1004. // the resultant variant type.
  1005. template <class... T>
  1006. class VariantStateBaseDestructorNontrivial;
  1007. template <class... T>
  1008. class VariantMoveBaseNontrivial;
  1009. template <class... T>
  1010. class VariantCopyBaseNontrivial;
  1011. template <class... T>
  1012. class VariantMoveAssignBaseNontrivial;
  1013. template <class... T>
  1014. class VariantCopyAssignBaseNontrivial;
  1015. // Base that is dependent on whether or not the destructor can be trivial.
  1016. template <class... T>
  1017. using VariantStateBaseDestructor =
  1018. absl::conditional_t<std::is_destructible<Union<T...>>::value,
  1019. VariantStateBase<T...>,
  1020. VariantStateBaseDestructorNontrivial<T...>>;
  1021. // Base that is dependent on whether or not the move-constructor can be
  1022. // implicitly generated by the compiler (trivial or deleted).
  1023. // Previously we were using `std::is_move_constructible<Union<T...>>` to check
  1024. // whether all Ts have trivial move constructor, but it ran into a GCC bug:
  1025. // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=84866
  1026. // So we have to use a different approach (i.e. `HasTrivialMoveConstructor`) to
  1027. // work around the bug.
  1028. template <class... T>
  1029. using VariantMoveBase = absl::conditional_t<
  1030. absl::disjunction<
  1031. absl::negation<absl::conjunction<std::is_move_constructible<T>...>>,
  1032. absl::conjunction<IsTriviallyMoveConstructible<T>...>>::value,
  1033. VariantStateBaseDestructor<T...>, VariantMoveBaseNontrivial<T...>>;
  1034. // Base that is dependent on whether or not the copy-constructor can be trivial.
  1035. template <class... T>
  1036. using VariantCopyBase = absl::conditional_t<
  1037. absl::disjunction<
  1038. absl::negation<absl::conjunction<std::is_copy_constructible<T>...>>,
  1039. std::is_copy_constructible<Union<T...>>>::value,
  1040. VariantMoveBase<T...>, VariantCopyBaseNontrivial<T...>>;
  1041. // Base that is dependent on whether or not the move-assign can be trivial.
  1042. template <class... T>
  1043. using VariantMoveAssignBase = absl::conditional_t<
  1044. absl::disjunction<absl::conjunction<std::is_move_assignable<Union<T...>>,
  1045. std::is_move_constructible<Union<T...>>,
  1046. std::is_destructible<Union<T...>>>,
  1047. absl::negation<absl::conjunction<
  1048. std::is_move_constructible<T>...,
  1049. std::is_move_assignable<T>...>>>::value,
  1050. VariantCopyBase<T...>, VariantMoveAssignBaseNontrivial<T...>>;
  1051. // Base that is dependent on whether or not the copy-assign can be trivial.
  1052. template <class... T>
  1053. using VariantCopyAssignBase = absl::conditional_t<
  1054. absl::disjunction<absl::conjunction<std::is_copy_assignable<Union<T...>>,
  1055. std::is_copy_constructible<Union<T...>>,
  1056. std::is_destructible<Union<T...>>>,
  1057. absl::negation<absl::conjunction<
  1058. std::is_copy_constructible<T>...,
  1059. std::is_copy_assignable<T>...>>>::value,
  1060. VariantMoveAssignBase<T...>, VariantCopyAssignBaseNontrivial<T...>>;
  1061. template <class... T>
  1062. using VariantBase = VariantCopyAssignBase<T...>;
  1063. template <class... T>
  1064. class VariantStateBaseDestructorNontrivial : protected VariantStateBase<T...> {
  1065. private:
  1066. using Base = VariantStateBase<T...>;
  1067. protected:
  1068. using Base::Base;
  1069. VariantStateBaseDestructorNontrivial() = default;
  1070. VariantStateBaseDestructorNontrivial(VariantStateBaseDestructorNontrivial&&) =
  1071. default;
  1072. VariantStateBaseDestructorNontrivial(
  1073. const VariantStateBaseDestructorNontrivial&) = default;
  1074. VariantStateBaseDestructorNontrivial& operator=(
  1075. VariantStateBaseDestructorNontrivial&&) = default;
  1076. VariantStateBaseDestructorNontrivial& operator=(
  1077. const VariantStateBaseDestructorNontrivial&) = default;
  1078. struct Destroyer {
  1079. template <std::size_t I>
  1080. void operator()(SizeT<I> i) const {
  1081. using Alternative =
  1082. typename absl::variant_alternative<I, variant<T...>>::type;
  1083. variant_internal::AccessUnion(self->state_, i).~Alternative();
  1084. }
  1085. void operator()(SizeT<absl::variant_npos> /*i*/) const {
  1086. // This space intentionally left blank
  1087. }
  1088. VariantStateBaseDestructorNontrivial* self;
  1089. };
  1090. void destroy() { VisitIndices<sizeof...(T)>::Run(Destroyer{this}, index_); }
  1091. ~VariantStateBaseDestructorNontrivial() { destroy(); }
  1092. protected:
  1093. using Base::index_;
  1094. using Base::state_;
  1095. };
  1096. template <class... T>
  1097. class VariantMoveBaseNontrivial : protected VariantStateBaseDestructor<T...> {
  1098. private:
  1099. using Base = VariantStateBaseDestructor<T...>;
  1100. protected:
  1101. using Base::Base;
  1102. struct Construct {
  1103. template <std::size_t I>
  1104. void operator()(SizeT<I> i) const {
  1105. using Alternative =
  1106. typename absl::variant_alternative<I, variant<T...>>::type;
  1107. ::new (static_cast<void*>(&self->state_)) Alternative(
  1108. variant_internal::AccessUnion(absl::move(other->state_), i));
  1109. }
  1110. void operator()(SizeT<absl::variant_npos> /*i*/) const {}
  1111. VariantMoveBaseNontrivial* self;
  1112. VariantMoveBaseNontrivial* other;
  1113. };
  1114. VariantMoveBaseNontrivial() = default;
  1115. VariantMoveBaseNontrivial(VariantMoveBaseNontrivial&& other) noexcept(
  1116. absl::conjunction<std::is_nothrow_move_constructible<T>...>::value)
  1117. : Base(NoopConstructorTag()) {
  1118. VisitIndices<sizeof...(T)>::Run(Construct{this, &other}, other.index_);
  1119. index_ = other.index_;
  1120. }
  1121. VariantMoveBaseNontrivial(VariantMoveBaseNontrivial const&) = default;
  1122. VariantMoveBaseNontrivial& operator=(VariantMoveBaseNontrivial&&) = default;
  1123. VariantMoveBaseNontrivial& operator=(VariantMoveBaseNontrivial const&) =
  1124. default;
  1125. protected:
  1126. using Base::index_;
  1127. using Base::state_;
  1128. };
  1129. template <class... T>
  1130. class VariantCopyBaseNontrivial : protected VariantMoveBase<T...> {
  1131. private:
  1132. using Base = VariantMoveBase<T...>;
  1133. protected:
  1134. using Base::Base;
  1135. VariantCopyBaseNontrivial() = default;
  1136. VariantCopyBaseNontrivial(VariantCopyBaseNontrivial&&) = default;
  1137. struct Construct {
  1138. template <std::size_t I>
  1139. void operator()(SizeT<I> i) const {
  1140. using Alternative =
  1141. typename absl::variant_alternative<I, variant<T...>>::type;
  1142. ::new (static_cast<void*>(&self->state_))
  1143. Alternative(variant_internal::AccessUnion(other->state_, i));
  1144. }
  1145. void operator()(SizeT<absl::variant_npos> /*i*/) const {}
  1146. VariantCopyBaseNontrivial* self;
  1147. const VariantCopyBaseNontrivial* other;
  1148. };
  1149. VariantCopyBaseNontrivial(VariantCopyBaseNontrivial const& other)
  1150. : Base(NoopConstructorTag()) {
  1151. VisitIndices<sizeof...(T)>::Run(Construct{this, &other}, other.index_);
  1152. index_ = other.index_;
  1153. }
  1154. VariantCopyBaseNontrivial& operator=(VariantCopyBaseNontrivial&&) = default;
  1155. VariantCopyBaseNontrivial& operator=(VariantCopyBaseNontrivial const&) =
  1156. default;
  1157. protected:
  1158. using Base::index_;
  1159. using Base::state_;
  1160. };
  1161. template <class... T>
  1162. class VariantMoveAssignBaseNontrivial : protected VariantCopyBase<T...> {
  1163. friend struct VariantCoreAccess;
  1164. private:
  1165. using Base = VariantCopyBase<T...>;
  1166. protected:
  1167. using Base::Base;
  1168. VariantMoveAssignBaseNontrivial() = default;
  1169. VariantMoveAssignBaseNontrivial(VariantMoveAssignBaseNontrivial&&) = default;
  1170. VariantMoveAssignBaseNontrivial(const VariantMoveAssignBaseNontrivial&) =
  1171. default;
  1172. VariantMoveAssignBaseNontrivial& operator=(
  1173. VariantMoveAssignBaseNontrivial const&) = default;
  1174. VariantMoveAssignBaseNontrivial&
  1175. operator=(VariantMoveAssignBaseNontrivial&& other) noexcept(
  1176. absl::conjunction<std::is_nothrow_move_constructible<T>...,
  1177. std::is_nothrow_move_assignable<T>...>::value) {
  1178. VisitIndices<sizeof...(T)>::Run(
  1179. VariantCoreAccess::MakeMoveAssignVisitor(this, &other), other.index_);
  1180. return *this;
  1181. }
  1182. protected:
  1183. using Base::index_;
  1184. using Base::state_;
  1185. };
  1186. template <class... T>
  1187. class VariantCopyAssignBaseNontrivial : protected VariantMoveAssignBase<T...> {
  1188. friend struct VariantCoreAccess;
  1189. private:
  1190. using Base = VariantMoveAssignBase<T...>;
  1191. protected:
  1192. using Base::Base;
  1193. VariantCopyAssignBaseNontrivial() = default;
  1194. VariantCopyAssignBaseNontrivial(VariantCopyAssignBaseNontrivial&&) = default;
  1195. VariantCopyAssignBaseNontrivial(const VariantCopyAssignBaseNontrivial&) =
  1196. default;
  1197. VariantCopyAssignBaseNontrivial& operator=(
  1198. VariantCopyAssignBaseNontrivial&&) = default;
  1199. VariantCopyAssignBaseNontrivial& operator=(
  1200. const VariantCopyAssignBaseNontrivial& other) {
  1201. VisitIndices<sizeof...(T)>::Run(
  1202. VariantCoreAccess::MakeCopyAssignVisitor(this, other), other.index_);
  1203. return *this;
  1204. }
  1205. protected:
  1206. using Base::index_;
  1207. using Base::state_;
  1208. };
  1209. ////////////////////////////////////////
  1210. // Visitors for Comparison Operations //
  1211. ////////////////////////////////////////
  1212. template <class... Types>
  1213. struct EqualsOp {
  1214. const variant<Types...>* v;
  1215. const variant<Types...>* w;
  1216. constexpr bool operator()(SizeT<absl::variant_npos> /*v_i*/) const {
  1217. return true;
  1218. }
  1219. template <std::size_t I>
  1220. constexpr bool operator()(SizeT<I> /*v_i*/) const {
  1221. return VariantCoreAccess::Access<I>(*v) == VariantCoreAccess::Access<I>(*w);
  1222. }
  1223. };
  1224. template <class... Types>
  1225. struct NotEqualsOp {
  1226. const variant<Types...>* v;
  1227. const variant<Types...>* w;
  1228. constexpr bool operator()(SizeT<absl::variant_npos> /*v_i*/) const {
  1229. return false;
  1230. }
  1231. template <std::size_t I>
  1232. constexpr bool operator()(SizeT<I> /*v_i*/) const {
  1233. return VariantCoreAccess::Access<I>(*v) != VariantCoreAccess::Access<I>(*w);
  1234. }
  1235. };
  1236. template <class... Types>
  1237. struct LessThanOp {
  1238. const variant<Types...>* v;
  1239. const variant<Types...>* w;
  1240. constexpr bool operator()(SizeT<absl::variant_npos> /*v_i*/) const {
  1241. return false;
  1242. }
  1243. template <std::size_t I>
  1244. constexpr bool operator()(SizeT<I> /*v_i*/) const {
  1245. return VariantCoreAccess::Access<I>(*v) < VariantCoreAccess::Access<I>(*w);
  1246. }
  1247. };
  1248. template <class... Types>
  1249. struct GreaterThanOp {
  1250. const variant<Types...>* v;
  1251. const variant<Types...>* w;
  1252. constexpr bool operator()(SizeT<absl::variant_npos> /*v_i*/) const {
  1253. return false;
  1254. }
  1255. template <std::size_t I>
  1256. constexpr bool operator()(SizeT<I> /*v_i*/) const {
  1257. return VariantCoreAccess::Access<I>(*v) > VariantCoreAccess::Access<I>(*w);
  1258. }
  1259. };
  1260. template <class... Types>
  1261. struct LessThanOrEqualsOp {
  1262. const variant<Types...>* v;
  1263. const variant<Types...>* w;
  1264. constexpr bool operator()(SizeT<absl::variant_npos> /*v_i*/) const {
  1265. return true;
  1266. }
  1267. template <std::size_t I>
  1268. constexpr bool operator()(SizeT<I> /*v_i*/) const {
  1269. return VariantCoreAccess::Access<I>(*v) <= VariantCoreAccess::Access<I>(*w);
  1270. }
  1271. };
  1272. template <class... Types>
  1273. struct GreaterThanOrEqualsOp {
  1274. const variant<Types...>* v;
  1275. const variant<Types...>* w;
  1276. constexpr bool operator()(SizeT<absl::variant_npos> /*v_i*/) const {
  1277. return true;
  1278. }
  1279. template <std::size_t I>
  1280. constexpr bool operator()(SizeT<I> /*v_i*/) const {
  1281. return VariantCoreAccess::Access<I>(*v) >= VariantCoreAccess::Access<I>(*w);
  1282. }
  1283. };
  1284. // Precondition: v.index() == w.index();
  1285. template <class... Types>
  1286. struct SwapSameIndex {
  1287. variant<Types...>* v;
  1288. variant<Types...>* w;
  1289. template <std::size_t I>
  1290. void operator()(SizeT<I>) const {
  1291. using std::swap;
  1292. swap(VariantCoreAccess::Access<I>(*v), VariantCoreAccess::Access<I>(*w));
  1293. }
  1294. void operator()(SizeT<variant_npos>) const {}
  1295. };
  1296. // TODO(calabrese) do this from a different namespace for proper adl usage
  1297. template <class... Types>
  1298. struct Swap {
  1299. variant<Types...>* v;
  1300. variant<Types...>* w;
  1301. void generic_swap() const {
  1302. variant<Types...> tmp(std::move(*w));
  1303. VariantCoreAccess::Destroy(*w);
  1304. VariantCoreAccess::InitFrom(*w, std::move(*v));
  1305. VariantCoreAccess::Destroy(*v);
  1306. VariantCoreAccess::InitFrom(*v, std::move(tmp));
  1307. }
  1308. void operator()(SizeT<absl::variant_npos> /*w_i*/) const {
  1309. if (!v->valueless_by_exception()) {
  1310. generic_swap();
  1311. }
  1312. }
  1313. template <std::size_t Wi>
  1314. void operator()(SizeT<Wi> /*w_i*/) {
  1315. if (v->index() == Wi) {
  1316. VisitIndices<sizeof...(Types)>::Run(SwapSameIndex<Types...>{v, w}, Wi);
  1317. } else {
  1318. generic_swap();
  1319. }
  1320. }
  1321. };
  1322. template <typename Variant, typename = void, typename... Ts>
  1323. struct VariantHashBase {
  1324. VariantHashBase() = delete;
  1325. VariantHashBase(const VariantHashBase&) = delete;
  1326. VariantHashBase(VariantHashBase&&) = delete;
  1327. VariantHashBase& operator=(const VariantHashBase&) = delete;
  1328. VariantHashBase& operator=(VariantHashBase&&) = delete;
  1329. };
  1330. struct VariantHashVisitor {
  1331. template <typename T>
  1332. size_t operator()(const T& t) {
  1333. return std::hash<T>{}(t);
  1334. }
  1335. };
  1336. template <typename Variant, typename... Ts>
  1337. struct VariantHashBase<Variant,
  1338. absl::enable_if_t<absl::conjunction<
  1339. type_traits_internal::IsHashEnabled<Ts>...>::value>,
  1340. Ts...> {
  1341. using argument_type = Variant;
  1342. using result_type = size_t;
  1343. size_t operator()(const Variant& var) const {
  1344. if (var.valueless_by_exception()) {
  1345. return 239799884;
  1346. }
  1347. size_t result = VisitIndices<variant_size<Variant>::value>::Run(
  1348. PerformVisitation<VariantHashVisitor, const Variant&>{
  1349. std::forward_as_tuple(var), VariantHashVisitor{}},
  1350. var.index());
  1351. // Combine the index and the hash result in order to distinguish
  1352. // std::variant<int, int> holding the same value as different alternative.
  1353. return result ^ var.index();
  1354. }
  1355. };
  1356. } // namespace variant_internal
  1357. } // inline namespace lts_2018_06_20
  1358. } // namespace absl
  1359. #endif // ABSL_TYPES_variant_internal_H_