xref: /netbsd-src/external/gpl3/gcc/dist/libstdc++-v3/include/std/variant (revision 181254a7b1bdde6873432bffef2d2decc4b5c22f)
1// <variant> -*- C++ -*-
2
3// Copyright (C) 2016-2019 Free Software Foundation, Inc.
4//
5// This file is part of the GNU ISO C++ Library.  This library is free
6// software; you can redistribute it and/or modify it under the
7// terms of the GNU General Public License as published by the
8// Free Software Foundation; either version 3, or (at your option)
9// any later version.
10
11// This library is distributed in the hope that it will be useful,
12// but WITHOUT ANY WARRANTY; without even the implied warranty of
13// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14// GNU General Public License for more details.
15
16// Under Section 7 of GPL version 3, you are granted additional
17// permissions described in the GCC Runtime Library Exception, version
18// 3.1, as published by the Free Software Foundation.
19
20// You should have received a copy of the GNU General Public License and
21// a copy of the GCC Runtime Library Exception along with this program;
22// see the files COPYING3 and COPYING.RUNTIME respectively.  If not, see
23// <http://www.gnu.org/licenses/>.
24
25/** @file variant
26 *  This is the <variant> C++ Library header.
27 */
28
29#ifndef _GLIBCXX_VARIANT
30#define _GLIBCXX_VARIANT 1
31
32#pragma GCC system_header
33
34#if __cplusplus >= 201703L
35
36#include <type_traits>
37#include <utility>
38#include <bits/enable_special_members.h>
39#include <bits/functexcept.h>
40#include <bits/move.h>
41#include <bits/functional_hash.h>
42#include <bits/invoke.h>
43#include <ext/aligned_buffer.h>
44#include <bits/parse_numbers.h>
45#include <bits/stl_iterator_base_types.h>
46#include <bits/stl_iterator_base_funcs.h>
47#include <bits/stl_construct.h>
48
49namespace std _GLIBCXX_VISIBILITY(default)
50{
51_GLIBCXX_BEGIN_NAMESPACE_VERSION
52
53namespace __detail
54{
55namespace __variant
56{
57  template<size_t _Np, typename... _Types>
58    struct _Nth_type;
59
60  template<size_t _Np, typename _First, typename... _Rest>
61    struct _Nth_type<_Np, _First, _Rest...>
62    : _Nth_type<_Np-1, _Rest...> { };
63
64  template<typename _First, typename... _Rest>
65    struct _Nth_type<0, _First, _Rest...>
66    { using type = _First; };
67
68} // namespace __variant
69} // namespace __detail
70
71#define __cpp_lib_variant 201606L
72
73  template<typename... _Types> class tuple;
74  template<typename... _Types> class variant;
75  template <typename> struct hash;
76
77  template<typename _Variant>
78    struct variant_size;
79
80  template<typename _Variant>
81    struct variant_size<const _Variant> : variant_size<_Variant> {};
82
83  template<typename _Variant>
84    struct variant_size<volatile _Variant> : variant_size<_Variant> {};
85
86  template<typename _Variant>
87    struct variant_size<const volatile _Variant> : variant_size<_Variant> {};
88
89  template<typename... _Types>
90    struct variant_size<variant<_Types...>>
91    : std::integral_constant<size_t, sizeof...(_Types)> {};
92
93  template<typename _Variant>
94    inline constexpr size_t variant_size_v = variant_size<_Variant>::value;
95
96  template<size_t _Np, typename _Variant>
97    struct variant_alternative;
98
99  template<size_t _Np, typename _First, typename... _Rest>
100    struct variant_alternative<_Np, variant<_First, _Rest...>>
101    : variant_alternative<_Np-1, variant<_Rest...>> {};
102
103  template<typename _First, typename... _Rest>
104    struct variant_alternative<0, variant<_First, _Rest...>>
105    { using type = _First; };
106
107  template<size_t _Np, typename _Variant>
108    using variant_alternative_t =
109      typename variant_alternative<_Np, _Variant>::type;
110
111  template<size_t _Np, typename _Variant>
112    struct variant_alternative<_Np, const _Variant>
113    { using type = add_const_t<variant_alternative_t<_Np, _Variant>>; };
114
115  template<size_t _Np, typename _Variant>
116    struct variant_alternative<_Np, volatile _Variant>
117    { using type = add_volatile_t<variant_alternative_t<_Np, _Variant>>; };
118
119  template<size_t _Np, typename _Variant>
120    struct variant_alternative<_Np, const volatile _Variant>
121    { using type = add_cv_t<variant_alternative_t<_Np, _Variant>>; };
122
123  inline constexpr size_t variant_npos = -1;
124
125  template<size_t _Np, typename... _Types>
126    constexpr variant_alternative_t<_Np, variant<_Types...>>&
127    get(variant<_Types...>&);
128
129  template<size_t _Np, typename... _Types>
130    constexpr variant_alternative_t<_Np, variant<_Types...>>&&
131    get(variant<_Types...>&&);
132
133  template<size_t _Np, typename... _Types>
134    constexpr variant_alternative_t<_Np, variant<_Types...>> const&
135    get(const variant<_Types...>&);
136
137  template<size_t _Np, typename... _Types>
138    constexpr variant_alternative_t<_Np, variant<_Types...>> const&&
139    get(const variant<_Types...>&&);
140
141  template<bool __use_index=false,
142	   bool __same_return_types = true,
143	   typename _Visitor, typename... _Variants>
144    constexpr decltype(auto)
145    __do_visit(_Visitor&& __visitor, _Variants&&... __variants);
146
147  template <typename... _Types, typename _Tp>
148    decltype(auto)
149    __variant_cast(_Tp&& __rhs)
150    {
151      if constexpr (is_lvalue_reference_v<_Tp>)
152	{
153	  if constexpr (is_const_v<remove_reference_t<_Tp>>)
154	    return static_cast<const variant<_Types...>&>(__rhs);
155	  else
156	    return static_cast<variant<_Types...>&>(__rhs);
157	}
158      else
159        return static_cast<variant<_Types...>&&>(__rhs);
160    }
161
162namespace __detail
163{
164namespace __variant
165{
166  // Returns the first apparence of _Tp in _Types.
167  // Returns sizeof...(_Types) if _Tp is not in _Types.
168  template<typename _Tp, typename... _Types>
169    struct __index_of : std::integral_constant<size_t, 0> {};
170
171  template<typename _Tp, typename... _Types>
172    inline constexpr size_t __index_of_v = __index_of<_Tp, _Types...>::value;
173
174  template<typename _Tp, typename _First, typename... _Rest>
175    struct __index_of<_Tp, _First, _Rest...> :
176      std::integral_constant<size_t, is_same_v<_Tp, _First>
177	? 0 : __index_of_v<_Tp, _Rest...> + 1> {};
178
179  // used for raw visitation
180  struct __variant_cookie {};
181  // used for raw visitation with indices passed in
182  struct __variant_idx_cookie { using type = __variant_idx_cookie; };
183  // a more explanatory name than 'true'
184  inline constexpr auto __visit_with_index = bool_constant<true>{};
185
186  // _Uninitialized<T> is guaranteed to be a literal type, even if T is not.
187  // We have to do this, because [basic.types]p10.5.3 (n4606) is not implemented
188  // yet. When it's implemented, _Uninitialized<T> can be changed to the alias
189  // to T, therefore equivalent to being removed entirely.
190  //
191  // Another reason we may not want to remove _Uninitialzied<T> may be that, we
192  // want _Uninitialized<T> to be trivially destructible, no matter whether T
193  // is; but we will see.
194  template<typename _Type, bool = std::is_literal_type_v<_Type>>
195    struct _Uninitialized;
196
197  template<typename _Type>
198    struct _Uninitialized<_Type, true>
199    {
200      template<typename... _Args>
201	constexpr
202	_Uninitialized(in_place_index_t<0>, _Args&&... __args)
203	: _M_storage(std::forward<_Args>(__args)...)
204	{ }
205
206      constexpr const _Type& _M_get() const & noexcept
207      { return _M_storage; }
208
209      constexpr _Type& _M_get() & noexcept
210      { return _M_storage; }
211
212      constexpr const _Type&& _M_get() const && noexcept
213      { return std::move(_M_storage); }
214
215      constexpr _Type&& _M_get() && noexcept
216      { return std::move(_M_storage); }
217
218      _Type _M_storage;
219    };
220
221  template<typename _Type>
222    struct _Uninitialized<_Type, false>
223    {
224      template<typename... _Args>
225	constexpr
226	_Uninitialized(in_place_index_t<0>, _Args&&... __args)
227	{
228	  ::new ((void*)std::addressof(_M_storage))
229	    _Type(std::forward<_Args>(__args)...);
230	}
231
232      const _Type& _M_get() const & noexcept
233      { return *_M_storage._M_ptr(); }
234
235      _Type& _M_get() & noexcept
236      { return *_M_storage._M_ptr(); }
237
238      const _Type&& _M_get() const && noexcept
239      { return std::move(*_M_storage._M_ptr()); }
240
241      _Type&& _M_get() && noexcept
242      { return std::move(*_M_storage._M_ptr()); }
243
244      __gnu_cxx::__aligned_membuf<_Type> _M_storage;
245    };
246
247  template<typename _Union>
248    constexpr decltype(auto)
249    __get(in_place_index_t<0>, _Union&& __u) noexcept
250    { return std::forward<_Union>(__u)._M_first._M_get(); }
251
252  template<size_t _Np, typename _Union>
253    constexpr decltype(auto)
254    __get(in_place_index_t<_Np>, _Union&& __u) noexcept
255    {
256      return __variant::__get(in_place_index<_Np-1>,
257			      std::forward<_Union>(__u)._M_rest);
258    }
259
260  // Returns the typed storage for __v.
261  template<size_t _Np, typename _Variant>
262    constexpr decltype(auto)
263    __get(_Variant&& __v) noexcept
264    {
265      return __variant::__get(std::in_place_index<_Np>,
266			      std::forward<_Variant>(__v)._M_u);
267    }
268
269  template<typename... _Types>
270    struct _Traits
271    {
272      static constexpr bool _S_default_ctor =
273	  is_default_constructible_v<typename _Nth_type<0, _Types...>::type>;
274      static constexpr bool _S_copy_ctor =
275	  (is_copy_constructible_v<_Types> && ...);
276      static constexpr bool _S_move_ctor =
277	  (is_move_constructible_v<_Types> && ...);
278      static constexpr bool _S_copy_assign =
279	  _S_copy_ctor
280	  && (is_copy_assignable_v<_Types> && ...);
281      static constexpr bool _S_move_assign =
282	  _S_move_ctor
283	  && (is_move_assignable_v<_Types> && ...);
284
285      static constexpr bool _S_trivial_dtor =
286	  (is_trivially_destructible_v<_Types> && ...);
287      static constexpr bool _S_trivial_copy_ctor =
288	  (is_trivially_copy_constructible_v<_Types> && ...);
289      static constexpr bool _S_trivial_move_ctor =
290	  (is_trivially_move_constructible_v<_Types> && ...);
291      static constexpr bool _S_trivial_copy_assign =
292	  _S_trivial_dtor && _S_trivial_copy_ctor
293	  && (is_trivially_copy_assignable_v<_Types> && ...);
294      static constexpr bool _S_trivial_move_assign =
295	  _S_trivial_dtor && _S_trivial_move_ctor
296	  && (is_trivially_move_assignable_v<_Types> && ...);
297
298      // The following nothrow traits are for non-trivial SMFs. Trivial SMFs
299      // are always nothrow.
300      static constexpr bool _S_nothrow_default_ctor =
301	  is_nothrow_default_constructible_v<
302	      typename _Nth_type<0, _Types...>::type>;
303      static constexpr bool _S_nothrow_copy_ctor = false;
304      static constexpr bool _S_nothrow_move_ctor =
305	  (is_nothrow_move_constructible_v<_Types> && ...);
306      static constexpr bool _S_nothrow_copy_assign = false;
307      static constexpr bool _S_nothrow_move_assign =
308	  _S_nothrow_move_ctor
309	  && (is_nothrow_move_assignable_v<_Types> && ...);
310    };
311
312  // Defines members and ctors.
313  template<typename... _Types>
314    union _Variadic_union { };
315
316  template<typename _First, typename... _Rest>
317    union _Variadic_union<_First, _Rest...>
318    {
319      constexpr _Variadic_union() : _M_rest() { }
320
321      template<typename... _Args>
322	constexpr _Variadic_union(in_place_index_t<0>, _Args&&... __args)
323	: _M_first(in_place_index<0>, std::forward<_Args>(__args)...)
324	{ }
325
326      template<size_t _Np, typename... _Args>
327	constexpr _Variadic_union(in_place_index_t<_Np>, _Args&&... __args)
328	: _M_rest(in_place_index<_Np-1>, std::forward<_Args>(__args)...)
329	{ }
330
331      _Uninitialized<_First> _M_first;
332      _Variadic_union<_Rest...> _M_rest;
333    };
334
335  // _Never_valueless_alt is true for variant alternatives that can
336  // always be placed in a variant without it becoming valueless.
337
338  // For suitably-small, trivially copyable types we can create temporaries
339  // on the stack and then memcpy them into place.
340  template<typename _Tp>
341    struct _Never_valueless_alt
342    : __and_<bool_constant<sizeof(_Tp) <= 256>, is_trivially_copyable<_Tp>>
343    { };
344
345  // Specialize _Never_valueless_alt for other types which have a
346  // non-throwing and cheap move construction and move assignment operator,
347  // so that emplacing the type will provide the strong exception-safety
348  // guarantee, by creating and moving a temporary.
349  // Whether _Never_valueless_alt<T> is true or not affects the ABI of a
350  // variant using that alternative, so we can't change the value later!
351
352  // True if every alternative in _Types... can be emplaced in a variant
353  // without it becoming valueless. If this is true, variant<_Types...>
354  // can never be valueless, which enables some minor optimizations.
355  template <typename... _Types>
356    constexpr bool __never_valueless()
357    {
358      return _Traits<_Types...>::_S_move_assign
359	&& (_Never_valueless_alt<_Types>::value && ...);
360    }
361
362  // Defines index and the dtor, possibly trivial.
363  template<bool __trivially_destructible, typename... _Types>
364    struct _Variant_storage;
365
366  template <typename... _Types>
367    using __select_index =
368      typename __select_int::_Select_int_base<sizeof...(_Types),
369					      unsigned char,
370					      unsigned short>::type::value_type;
371
372  template<typename... _Types>
373    struct _Variant_storage<false, _Types...>
374    {
375      constexpr _Variant_storage() : _M_index(variant_npos) { }
376
377      template<size_t _Np, typename... _Args>
378	constexpr _Variant_storage(in_place_index_t<_Np>, _Args&&... __args)
379	: _M_u(in_place_index<_Np>, std::forward<_Args>(__args)...),
380	_M_index(_Np)
381	{ }
382
383      constexpr void _M_reset_impl()
384      {
385	__do_visit([](auto&& __this_mem) mutable
386		   -> __detail::__variant::__variant_cookie
387	  {
388	    if constexpr (!is_same_v<remove_reference_t<decltype(__this_mem)>,
389			  __variant_cookie>)
390	      std::_Destroy(std::__addressof(__this_mem));
391	    return {};
392	  }, __variant_cast<_Types...>(*this));
393      }
394
395      void _M_reset()
396      {
397	_M_reset_impl();
398	_M_index = variant_npos;
399      }
400
401      ~_Variant_storage()
402      { _M_reset(); }
403
404      void*
405      _M_storage() const
406      {
407	return const_cast<void*>(static_cast<const void*>(
408	    std::addressof(_M_u)));
409      }
410
411      constexpr bool
412      _M_valid() const noexcept
413      {
414	if constexpr (__never_valueless<_Types...>())
415	  return true;
416	return this->_M_index != __index_type(variant_npos);
417      }
418
419      _Variadic_union<_Types...> _M_u;
420      using __index_type = __select_index<_Types...>;
421      __index_type _M_index;
422    };
423
424  template<typename... _Types>
425    struct _Variant_storage<true, _Types...>
426    {
427      constexpr _Variant_storage() : _M_index(variant_npos) { }
428
429      template<size_t _Np, typename... _Args>
430	constexpr _Variant_storage(in_place_index_t<_Np>, _Args&&... __args)
431	: _M_u(in_place_index<_Np>, std::forward<_Args>(__args)...),
432	_M_index(_Np)
433	{ }
434
435      void _M_reset()
436      { _M_index = variant_npos; }
437
438      void*
439      _M_storage() const
440      {
441	return const_cast<void*>(static_cast<const void*>(
442	    std::addressof(_M_u)));
443      }
444
445      constexpr bool
446      _M_valid() const noexcept
447      {
448	if constexpr (__never_valueless<_Types...>())
449	  return true;
450	return this->_M_index != __index_type(variant_npos);
451      }
452
453      _Variadic_union<_Types...> _M_u;
454      using __index_type = __select_index<_Types...>;
455      __index_type _M_index;
456    };
457
458  template<typename... _Types>
459    using _Variant_storage_alias =
460	_Variant_storage<_Traits<_Types...>::_S_trivial_dtor, _Types...>;
461
462  template<typename _Tp, typename _Up>
463    void __variant_construct_single(_Tp&& __lhs, _Up&& __rhs_mem)
464    {
465      void* __storage = std::addressof(__lhs._M_u);
466      using _Type = remove_reference_t<decltype(__rhs_mem)>;
467      if constexpr (!is_same_v<_Type, __variant_cookie>)
468        ::new (__storage)
469	  _Type(std::forward<decltype(__rhs_mem)>(__rhs_mem));
470    }
471
472  template<typename... _Types, typename _Tp, typename _Up>
473    void __variant_construct(_Tp&& __lhs, _Up&& __rhs)
474    {
475      __lhs._M_index = __rhs._M_index;
476      __do_visit([&__lhs](auto&& __rhs_mem) mutable
477		 -> __detail::__variant::__variant_cookie
478        {
479	  __variant_construct_single(std::forward<_Tp>(__lhs),
480	      std::forward<decltype(__rhs_mem)>(__rhs_mem));
481	  return {};
482	}, __variant_cast<_Types...>(std::forward<_Up>(__rhs)));
483    }
484
485  // The following are (Copy|Move) (ctor|assign) layers for forwarding
486  // triviality and handling non-trivial SMF behaviors.
487
488  template<bool, typename... _Types>
489    struct _Copy_ctor_base : _Variant_storage_alias<_Types...>
490    {
491      using _Base = _Variant_storage_alias<_Types...>;
492      using _Base::_Base;
493
494      _Copy_ctor_base(const _Copy_ctor_base& __rhs)
495	  noexcept(_Traits<_Types...>::_S_nothrow_copy_ctor)
496      {
497	__variant_construct<_Types...>(*this, __rhs);
498      }
499
500      _Copy_ctor_base(_Copy_ctor_base&&) = default;
501      _Copy_ctor_base& operator=(const _Copy_ctor_base&) = default;
502      _Copy_ctor_base& operator=(_Copy_ctor_base&&) = default;
503    };
504
505  template<typename... _Types>
506    struct _Copy_ctor_base<true, _Types...> : _Variant_storage_alias<_Types...>
507    {
508      using _Base = _Variant_storage_alias<_Types...>;
509      using _Base::_Base;
510    };
511
512  template<typename... _Types>
513    using _Copy_ctor_alias =
514	_Copy_ctor_base<_Traits<_Types...>::_S_trivial_copy_ctor, _Types...>;
515
516  template<bool, typename... _Types>
517    struct _Move_ctor_base : _Copy_ctor_alias<_Types...>
518    {
519      using _Base = _Copy_ctor_alias<_Types...>;
520      using _Base::_Base;
521
522      _Move_ctor_base(_Move_ctor_base&& __rhs)
523	  noexcept(_Traits<_Types...>::_S_nothrow_move_ctor)
524      {
525	__variant_construct<_Types...>(*this, std::move(__rhs));
526      }
527
528      template<typename _Up>
529        void _M_destructive_move(unsigned short __rhs_index, _Up&& __rhs)
530        {
531	  this->_M_reset();
532	  __variant_construct_single(*this, std::forward<_Up>(__rhs));
533	  this->_M_index = __rhs_index;
534	}
535
536      template<typename _Up>
537        void _M_destructive_copy(unsigned short __rhs_index, const _Up& __rhs)
538        {
539	  this->_M_reset();
540	  __variant_construct_single(*this, __rhs);
541	  this->_M_index = __rhs_index;
542	}
543
544      _Move_ctor_base(const _Move_ctor_base&) = default;
545      _Move_ctor_base& operator=(const _Move_ctor_base&) = default;
546      _Move_ctor_base& operator=(_Move_ctor_base&&) = default;
547    };
548
549  template<typename... _Types>
550    struct _Move_ctor_base<true, _Types...> : _Copy_ctor_alias<_Types...>
551    {
552      using _Base = _Copy_ctor_alias<_Types...>;
553      using _Base::_Base;
554
555      template<typename _Up>
556        void _M_destructive_move(unsigned short __rhs_index, _Up&& __rhs)
557        {
558	  this->_M_reset();
559	  __variant_construct_single(*this, std::forward<_Up>(__rhs));
560	  this->_M_index = __rhs_index;
561	}
562
563      template<typename _Up>
564        void _M_destructive_copy(unsigned short __rhs_index, const _Up& __rhs)
565        {
566	  this->_M_reset();
567	  __variant_construct_single(*this, __rhs);
568	  this->_M_index = __rhs_index;
569	}
570    };
571
572  template<typename... _Types>
573    using _Move_ctor_alias =
574	_Move_ctor_base<_Traits<_Types...>::_S_trivial_move_ctor, _Types...>;
575
576  template<bool, typename... _Types>
577    struct _Copy_assign_base : _Move_ctor_alias<_Types...>
578    {
579      using _Base = _Move_ctor_alias<_Types...>;
580      using _Base::_Base;
581
582      _Copy_assign_base&
583      operator=(const _Copy_assign_base& __rhs)
584	  noexcept(_Traits<_Types...>::_S_nothrow_copy_assign)
585      {
586	__do_visit<__visit_with_index>([this](auto&& __rhs_mem,
587					      auto __rhs_index) mutable
588	    -> __detail::__variant::__variant_idx_cookie
589	  {
590	    if constexpr (__rhs_index != variant_npos)
591	      {
592		if (this->_M_index == __rhs_index)
593		  __variant::__get<__rhs_index>(*this) = __rhs_mem;
594		else
595		  {
596		    using __rhs_type = __remove_cvref_t<decltype(__rhs_mem)>;
597		    if constexpr (is_nothrow_copy_constructible_v<__rhs_type>
598			|| !is_nothrow_move_constructible_v<__rhs_type>)
599		      // The standard says this->emplace<__rhs_type>(__rhs_mem)
600		      // should be used here, but _M_destructive_copy is
601		      // equivalent in this case. Either copy construction
602		      // doesn't throw, so _M_destructive_copy gives strong
603		      // exception safety guarantee, or both copy construction
604		      // and move construction can throw, so emplace only gives
605		      // basic exception safety anyway.
606		      this->_M_destructive_copy(__rhs_index, __rhs_mem);
607		    else
608		      __variant_cast<_Types...>(*this)
609			= variant<_Types...>(__rhs_mem);
610		  }
611	      }
612	    else
613	      this->_M_reset();
614	    return {};
615	  }, __variant_cast<_Types...>(__rhs));
616	return *this;
617      }
618
619      _Copy_assign_base(const _Copy_assign_base&) = default;
620      _Copy_assign_base(_Copy_assign_base&&) = default;
621      _Copy_assign_base& operator=(_Copy_assign_base&&) = default;
622    };
623
624  template<typename... _Types>
625    struct _Copy_assign_base<true, _Types...> : _Move_ctor_alias<_Types...>
626    {
627      using _Base = _Move_ctor_alias<_Types...>;
628      using _Base::_Base;
629    };
630
631  template<typename... _Types>
632    using _Copy_assign_alias =
633      _Copy_assign_base<_Traits<_Types...>::_S_trivial_copy_assign, _Types...>;
634
635  template<bool, typename... _Types>
636    struct _Move_assign_base : _Copy_assign_alias<_Types...>
637    {
638      using _Base = _Copy_assign_alias<_Types...>;
639      using _Base::_Base;
640
641      _Move_assign_base&
642      operator=(_Move_assign_base&& __rhs)
643	  noexcept(_Traits<_Types...>::_S_nothrow_move_assign)
644      {
645	__do_visit<__visit_with_index>([this](auto&& __rhs_mem,
646					      auto __rhs_index) mutable
647	    -> __detail::__variant::__variant_idx_cookie
648	  {
649	    if constexpr (__rhs_index != variant_npos)
650	      {
651		if (this->_M_index == __rhs_index)
652		  __variant::__get<__rhs_index>(*this) = std::move(__rhs_mem);
653		else
654		  __variant_cast<_Types...>(*this)
655		    .template emplace<__rhs_index>(std::move(__rhs_mem));
656	      }
657	    else
658	      this->_M_reset();
659	    return {};
660	  }, __variant_cast<_Types...>(__rhs));
661	return *this;
662      }
663
664      _Move_assign_base(const _Move_assign_base&) = default;
665      _Move_assign_base(_Move_assign_base&&) = default;
666      _Move_assign_base& operator=(const _Move_assign_base&) = default;
667    };
668
669  template<typename... _Types>
670    struct _Move_assign_base<true, _Types...> : _Copy_assign_alias<_Types...>
671    {
672      using _Base = _Copy_assign_alias<_Types...>;
673      using _Base::_Base;
674    };
675
676  template<typename... _Types>
677    using _Move_assign_alias =
678      _Move_assign_base<_Traits<_Types...>::_S_trivial_move_assign, _Types...>;
679
680  template<typename... _Types>
681    struct _Variant_base : _Move_assign_alias<_Types...>
682    {
683      using _Base = _Move_assign_alias<_Types...>;
684
685      constexpr
686      _Variant_base()
687	  noexcept(_Traits<_Types...>::_S_nothrow_default_ctor)
688      : _Variant_base(in_place_index<0>) { }
689
690      template<size_t _Np, typename... _Args>
691	constexpr explicit
692	_Variant_base(in_place_index_t<_Np> __i, _Args&&... __args)
693	: _Base(__i, std::forward<_Args>(__args)...)
694	{ }
695
696      _Variant_base(const _Variant_base&) = default;
697      _Variant_base(_Variant_base&&) = default;
698      _Variant_base& operator=(const _Variant_base&) = default;
699      _Variant_base& operator=(_Variant_base&&) = default;
700    };
701
702  // For how many times does _Tp appear in _Tuple?
703  template<typename _Tp, typename _Tuple>
704    struct __tuple_count;
705
706  template<typename _Tp, typename _Tuple>
707    inline constexpr size_t __tuple_count_v =
708      __tuple_count<_Tp, _Tuple>::value;
709
710  template<typename _Tp, typename... _Types>
711    struct __tuple_count<_Tp, tuple<_Types...>>
712    : integral_constant<size_t, 0> { };
713
714  template<typename _Tp, typename _First, typename... _Rest>
715    struct __tuple_count<_Tp, tuple<_First, _Rest...>>
716    : integral_constant<
717	size_t,
718	__tuple_count_v<_Tp, tuple<_Rest...>> + is_same_v<_Tp, _First>> { };
719
720  // TODO: Reuse this in <tuple> ?
721  template<typename _Tp, typename... _Types>
722    inline constexpr bool __exactly_once =
723      __tuple_count_v<_Tp, tuple<_Types...>> == 1;
724
725  // Takes _Types and create an overloaded _S_fun for each type.
726  // If a type appears more than once in _Types, create only one overload.
727  template<typename... _Types>
728    struct __overload_set
729    { static void _S_fun(); };
730
731  template<typename _First, typename... _Rest>
732    struct __overload_set<_First, _Rest...> : __overload_set<_Rest...>
733    {
734      using __overload_set<_Rest...>::_S_fun;
735      static integral_constant<size_t, sizeof...(_Rest)> _S_fun(_First);
736    };
737
738  template<typename... _Rest>
739    struct __overload_set<void, _Rest...> : __overload_set<_Rest...>
740    {
741      using __overload_set<_Rest...>::_S_fun;
742    };
743
744  // Helper for variant(_Tp&&) and variant::operator=(_Tp&&).
745  // __accepted_index maps an arbitrary _Tp to an alternative type in _Variant
746  // (or to variant_npos).
747  template<typename _Tp, typename _Variant, typename = void>
748    struct __accepted_index
749    { static constexpr size_t value = variant_npos; };
750
751  template<typename _Tp, typename... _Types>
752    struct __accepted_index<
753      _Tp, variant<_Types...>,
754      void_t<decltype(__overload_set<_Types...>::_S_fun(std::declval<_Tp>()))>>
755    {
756      static constexpr size_t value = sizeof...(_Types) - 1
757	- decltype(__overload_set<_Types...>::
758		   _S_fun(std::declval<_Tp>()))::value;
759    };
760
761  // Returns the raw storage for __v.
762  template<typename _Variant>
763    void* __get_storage(_Variant&& __v)
764    { return __v._M_storage(); }
765
766  template <typename _Maybe_variant_cookie, typename _Variant>
767    struct _Extra_visit_slot_needed
768    {
769      template <typename> struct _Variant_never_valueless;
770
771      template <typename... _Types>
772	struct _Variant_never_valueless<variant<_Types...>>
773	: bool_constant<__never_valueless<_Types...>()> {};
774
775      static constexpr bool value =
776	(is_same_v<_Maybe_variant_cookie, __variant_cookie>
777	 || is_same_v<_Maybe_variant_cookie, __variant_idx_cookie>)
778	&& !_Variant_never_valueless<__remove_cvref_t<_Variant>>::value;
779    };
780
781  // Used for storing a multi-dimensional vtable.
782  template<typename _Tp, size_t... _Dimensions>
783    struct _Multi_array;
784
785  // Partial specialization with rank zero, stores a single _Tp element.
786  template<typename _Tp>
787    struct _Multi_array<_Tp>
788    {
789      constexpr const _Tp&
790      _M_access() const
791      { return _M_data; }
792
793      _Tp _M_data;
794    };
795
796  // Partial specialization with rank >= 1.
797  template<typename _Ret,
798	   typename _Visitor,
799	   typename... _Variants,
800	   size_t __first, size_t... __rest>
801    struct _Multi_array<_Ret(*)(_Visitor, _Variants...), __first, __rest...>
802    {
803      static constexpr size_t __index =
804	sizeof...(_Variants) - sizeof...(__rest) - 1;
805
806      using _Variant = typename _Nth_type<__index, _Variants...>::type;
807
808      static constexpr int __do_cookie =
809	_Extra_visit_slot_needed<_Ret, _Variant>::value ? 1 : 0;
810
811      using _Tp = _Ret(*)(_Visitor, _Variants...);
812
813      template<typename... _Args>
814	constexpr const _Tp&
815	_M_access(size_t __first_index, _Args... __rest_indices) const
816        {
817	  return _M_arr[__first_index + __do_cookie]
818	    ._M_access(__rest_indices...);
819	}
820
821      _Multi_array<_Tp, __rest...> _M_arr[__first + __do_cookie];
822    };
823
824  // Creates a multi-dimensional vtable recursively.
825  //
826  // The __same_return_types non-type template parameter specifies whether
827  // to enforce that all visitor invocations return the same type. This is
828  // required by std::visit but not std::visit<R>.
829  //
830  // For example,
831  // visit([](auto, auto){},
832  //       variant<int, char>(),  // typedef'ed as V1
833  //       variant<float, double, long double>())  // typedef'ed as V2
834  // will trigger instantiations of:
835  // __gen_vtable_impl<true, _Multi_array<void(*)(V1&&, V2&&), 2, 3>,
836  //                   tuple<V1&&, V2&&>, std::index_sequence<>>
837  //   __gen_vtable_impl<true, _Multi_array<void(*)(V1&&, V2&&), 3>,
838  //                     tuple<V1&&, V2&&>, std::index_sequence<0>>
839  //     __gen_vtable_impl<true, _Multi_array<void(*)(V1&&, V2&&)>,
840  //                       tuple<V1&&, V2&&>, std::index_sequence<0, 0>>
841  //     __gen_vtable_impl<true, _Multi_array<void(*)(V1&&, V2&&)>,
842  //                       tuple<V1&&, V2&&>, std::index_sequence<0, 1>>
843  //     __gen_vtable_impl<true, _Multi_array<void(*)(V1&&, V2&&)>,
844  //                       tuple<V1&&, V2&&>, std::index_sequence<0, 2>>
845  //   __gen_vtable_impl<true, _Multi_array<void(*)(V1&&, V2&&), 3>,
846  //                     tuple<V1&&, V2&&>, std::index_sequence<1>>
847  //     __gen_vtable_impl<true, _Multi_array<void(*)(V1&&, V2&&)>,
848  //                       tuple<V1&&, V2&&>, std::index_sequence<1, 0>>
849  //     __gen_vtable_impl<true, _Multi_array<void(*)(V1&&, V2&&)>,
850  //                       tuple<V1&&, V2&&>, std::index_sequence<1, 1>>
851  //     __gen_vtable_impl<true, _Multi_array<void(*)(V1&&, V2&&)>,
852  //                       tuple<V1&&, V2&&>, std::index_sequence<1, 2>>
853  // The returned multi-dimensional vtable can be fast accessed by the visitor
854  // using index calculation.
855  template<bool __same_return_types,
856	   typename _Array_type, typename _Variant_tuple, typename _Index_seq>
857    struct __gen_vtable_impl;
858
859  // Defines the _S_apply() member that returns a _Multi_array populated
860  // with function pointers that perform the visitation expressions e(m)
861  // for each valid pack of indexes into the variant types _Variants.
862  //
863  // This partial specialization builds up the index sequences by recursively
864  // calling _S_apply() on the next specialization of __gen_vtable_impl.
865  // The base case of the recursion defines the actual function pointers.
866  template<bool __same_return_types,
867	   typename _Result_type, typename _Visitor, size_t... __dimensions,
868	   typename... _Variants, size_t... __indices>
869    struct __gen_vtable_impl<
870        __same_return_types,
871	_Multi_array<_Result_type (*)(_Visitor, _Variants...), __dimensions...>,
872	tuple<_Variants...>, std::index_sequence<__indices...>>
873    {
874      using _Next =
875	  remove_reference_t<typename _Nth_type<sizeof...(__indices),
876			     _Variants...>::type>;
877      using _Array_type =
878	  _Multi_array<_Result_type (*)(_Visitor, _Variants...),
879		       __dimensions...>;
880
881      static constexpr _Array_type
882      _S_apply()
883      {
884	_Array_type __vtable{};
885	_S_apply_all_alts(
886	  __vtable, make_index_sequence<variant_size_v<_Next>>());
887	return __vtable;
888      }
889
890      template<size_t... __var_indices>
891	static constexpr void
892	_S_apply_all_alts(_Array_type& __vtable,
893			  std::index_sequence<__var_indices...>)
894	{
895	  if constexpr (_Extra_visit_slot_needed<_Result_type, _Next>::value)
896	    (_S_apply_single_alt<true, __var_indices>(
897	      __vtable._M_arr[__var_indices + 1],
898	      &(__vtable._M_arr[0])), ...);
899	  else
900	    (_S_apply_single_alt<false, __var_indices>(
901	      __vtable._M_arr[__var_indices]), ...);
902	}
903
904      template<bool __do_cookie, size_t __index, typename _Tp>
905	static constexpr void
906	_S_apply_single_alt(_Tp& __element, _Tp* __cookie_element = nullptr)
907	{
908	  using _Alternative = variant_alternative_t<__index, _Next>;
909	  if constexpr (__do_cookie)
910	    {
911	      __element = __gen_vtable_impl<
912		__same_return_types,
913		_Tp,
914		tuple<_Variants...>,
915		std::index_sequence<__indices..., __index>>::_S_apply();
916	      *__cookie_element = __gen_vtable_impl<
917		__same_return_types,
918		_Tp,
919		tuple<_Variants...>,
920		std::index_sequence<__indices..., variant_npos>>::_S_apply();
921	    }
922	  else
923	    {
924	      __element = __gen_vtable_impl<
925		__same_return_types,
926		remove_reference_t<decltype(__element)>, tuple<_Variants...>,
927		std::index_sequence<__indices..., __index>>::_S_apply();
928	    }
929	}
930    };
931
932  // This partial specialization is the base case for the recursion.
933  // It populates a _Multi_array element with the address of a function
934  // that invokes the visitor with the alternatives specified by __indices.
935  template<bool __same_return_types,
936	   typename _Result_type, typename _Visitor, typename... _Variants,
937	   size_t... __indices>
938    struct __gen_vtable_impl<
939      __same_return_types,
940      _Multi_array<_Result_type (*)(_Visitor, _Variants...)>,
941		   tuple<_Variants...>, std::index_sequence<__indices...>>
942    {
943      using _Array_type =
944	  _Multi_array<_Result_type (*)(_Visitor, _Variants...)>;
945
946      template<size_t __index, typename _Variant>
947	static constexpr decltype(auto)
948	__element_by_index_or_cookie(_Variant&& __var) noexcept
949        {
950	  if constexpr (__index != variant_npos)
951	    return __variant::__get<__index>(std::forward<_Variant>(__var));
952	  else
953	    return __variant_cookie{};
954	}
955
956      static constexpr decltype(auto)
957      __visit_invoke_impl(_Visitor&& __visitor, _Variants... __vars)
958      {
959	// For raw visitation using indices, pass the indices to the visitor:
960	if constexpr (is_same_v<_Result_type, __variant_idx_cookie>)
961	  return std::__invoke(std::forward<_Visitor>(__visitor),
962	      __element_by_index_or_cookie<__indices>(
963		std::forward<_Variants>(__vars))...,
964	      integral_constant<size_t, __indices>()...);
965	// For std::visit<cv void>, cast the result to void:
966	else if constexpr (!__same_return_types &&
967			   std::is_void_v<_Result_type>)
968	  return (void)std::__invoke(std::forward<_Visitor>(__visitor),
969	      __element_by_index_or_cookie<__indices>(
970		std::forward<_Variants>(__vars))...);
971	else
972	  return std::__invoke(std::forward<_Visitor>(__visitor),
973	      __element_by_index_or_cookie<__indices>(
974		std::forward<_Variants>(__vars))...);
975      }
976
977      static constexpr decltype(auto)
978      __do_visit_invoke(_Visitor&& __visitor, _Variants... __vars)
979      {
980	return __visit_invoke_impl(std::forward<_Visitor>(__visitor),
981				   std::forward<_Variants>(__vars)...);
982      }
983
984      // Perform the implicit conversion to _Result_type for std::visit<R>.
985      static constexpr _Result_type
986      __do_visit_invoke_r(_Visitor&& __visitor, _Variants... __vars)
987      {
988	return __visit_invoke_impl(std::forward<_Visitor>(__visitor),
989				   std::forward<_Variants>(__vars)...);
990      }
991
992      static constexpr decltype(auto)
993      __visit_invoke(_Visitor&& __visitor, _Variants... __vars)
994      {
995	if constexpr (__same_return_types)
996	  return __do_visit_invoke(std::forward<_Visitor>(__visitor),
997				   std::forward<_Variants>(__vars)...);
998	else
999	  return __do_visit_invoke_r(std::forward<_Visitor>(__visitor),
1000				     std::forward<_Variants>(__vars)...);
1001      }
1002
1003      static constexpr auto
1004      _S_apply()
1005      { return _Array_type{&__visit_invoke}; }
1006    };
1007
1008  template<bool __same_return_types,
1009	   typename _Result_type, typename _Visitor, typename... _Variants>
1010    struct __gen_vtable
1011    {
1012      using _Array_type =
1013	  _Multi_array<_Result_type (*)(_Visitor, _Variants...),
1014		       variant_size_v<remove_reference_t<_Variants>>...>;
1015
1016      static constexpr _Array_type _S_vtable
1017	= __gen_vtable_impl<__same_return_types,
1018			    _Array_type, tuple<_Variants...>,
1019			    std::index_sequence<>>::_S_apply();
1020    };
1021
1022  template<size_t _Np, typename _Tp>
1023    struct _Base_dedup : public _Tp { };
1024
1025  template<typename _Variant, typename __indices>
1026    struct _Variant_hash_base;
1027
1028  template<typename... _Types, size_t... __indices>
1029    struct _Variant_hash_base<variant<_Types...>,
1030			      std::index_sequence<__indices...>>
1031    : _Base_dedup<__indices, __poison_hash<remove_const_t<_Types>>>... { };
1032
1033} // namespace __variant
1034} // namespace __detail
1035
1036  template<size_t _Np, typename _Variant, typename... _Args>
1037    void __variant_construct_by_index(_Variant& __v, _Args&&... __args)
1038    {
1039      __v._M_index = _Np;
1040      auto&& __storage = __detail::__variant::__get<_Np>(__v);
1041      ::new ((void*)std::addressof(__storage))
1042        remove_reference_t<decltype(__storage)>
1043	  (std::forward<_Args>(__args)...);
1044    }
1045
1046  template<typename _Tp, typename... _Types>
1047    constexpr bool
1048    holds_alternative(const variant<_Types...>& __v) noexcept
1049    {
1050      static_assert(__detail::__variant::__exactly_once<_Tp, _Types...>,
1051		    "T should occur for exactly once in alternatives");
1052      return __v.index() == __detail::__variant::__index_of_v<_Tp, _Types...>;
1053    }
1054
1055  template<typename _Tp, typename... _Types>
1056    constexpr _Tp& get(variant<_Types...>& __v)
1057    {
1058      static_assert(__detail::__variant::__exactly_once<_Tp, _Types...>,
1059		    "T should occur for exactly once in alternatives");
1060      static_assert(!is_void_v<_Tp>, "_Tp should not be void");
1061      return std::get<__detail::__variant::__index_of_v<_Tp, _Types...>>(__v);
1062    }
1063
1064  template<typename _Tp, typename... _Types>
1065    constexpr _Tp&& get(variant<_Types...>&& __v)
1066    {
1067      static_assert(__detail::__variant::__exactly_once<_Tp, _Types...>,
1068		    "T should occur for exactly once in alternatives");
1069      static_assert(!is_void_v<_Tp>, "_Tp should not be void");
1070      return std::get<__detail::__variant::__index_of_v<_Tp, _Types...>>(
1071	std::move(__v));
1072    }
1073
1074  template<typename _Tp, typename... _Types>
1075    constexpr const _Tp& get(const variant<_Types...>& __v)
1076    {
1077      static_assert(__detail::__variant::__exactly_once<_Tp, _Types...>,
1078		    "T should occur for exactly once in alternatives");
1079      static_assert(!is_void_v<_Tp>, "_Tp should not be void");
1080      return std::get<__detail::__variant::__index_of_v<_Tp, _Types...>>(__v);
1081    }
1082
1083  template<typename _Tp, typename... _Types>
1084    constexpr const _Tp&& get(const variant<_Types...>&& __v)
1085    {
1086      static_assert(__detail::__variant::__exactly_once<_Tp, _Types...>,
1087		    "T should occur for exactly once in alternatives");
1088      static_assert(!is_void_v<_Tp>, "_Tp should not be void");
1089      return std::get<__detail::__variant::__index_of_v<_Tp, _Types...>>(
1090	std::move(__v));
1091    }
1092
1093  template<size_t _Np, typename... _Types>
1094    constexpr add_pointer_t<variant_alternative_t<_Np, variant<_Types...>>>
1095    get_if(variant<_Types...>* __ptr) noexcept
1096    {
1097      using _Alternative_type = variant_alternative_t<_Np, variant<_Types...>>;
1098      static_assert(_Np < sizeof...(_Types),
1099		    "The index should be in [0, number of alternatives)");
1100      static_assert(!is_void_v<_Alternative_type>, "_Tp should not be void");
1101      if (__ptr && __ptr->index() == _Np)
1102	return std::addressof(__detail::__variant::__get<_Np>(*__ptr));
1103      return nullptr;
1104    }
1105
1106  template<size_t _Np, typename... _Types>
1107    constexpr
1108    add_pointer_t<const variant_alternative_t<_Np, variant<_Types...>>>
1109    get_if(const variant<_Types...>* __ptr) noexcept
1110    {
1111      using _Alternative_type = variant_alternative_t<_Np, variant<_Types...>>;
1112      static_assert(_Np < sizeof...(_Types),
1113		    "The index should be in [0, number of alternatives)");
1114      static_assert(!is_void_v<_Alternative_type>, "_Tp should not be void");
1115      if (__ptr && __ptr->index() == _Np)
1116	return std::addressof(__detail::__variant::__get<_Np>(*__ptr));
1117      return nullptr;
1118    }
1119
1120  template<typename _Tp, typename... _Types>
1121    constexpr add_pointer_t<_Tp>
1122    get_if(variant<_Types...>* __ptr) noexcept
1123    {
1124      static_assert(__detail::__variant::__exactly_once<_Tp, _Types...>,
1125		    "T should occur for exactly once in alternatives");
1126      static_assert(!is_void_v<_Tp>, "_Tp should not be void");
1127      return std::get_if<__detail::__variant::__index_of_v<_Tp, _Types...>>(
1128	  __ptr);
1129    }
1130
1131  template<typename _Tp, typename... _Types>
1132    constexpr add_pointer_t<const _Tp>
1133    get_if(const variant<_Types...>* __ptr) noexcept
1134    {
1135      static_assert(__detail::__variant::__exactly_once<_Tp, _Types...>,
1136		    "T should occur for exactly once in alternatives");
1137      static_assert(!is_void_v<_Tp>, "_Tp should not be void");
1138      return std::get_if<__detail::__variant::__index_of_v<_Tp, _Types...>>(
1139	  __ptr);
1140    }
1141
1142  struct monostate { };
1143
1144#define _VARIANT_RELATION_FUNCTION_TEMPLATE(__OP, __NAME) \
1145  template<typename... _Types> \
1146    constexpr bool operator __OP(const variant<_Types...>& __lhs, \
1147				 const variant<_Types...>& __rhs) \
1148    { \
1149      bool __ret = true; \
1150      __do_visit<__detail::__variant::__visit_with_index>( \
1151        [&__ret, &__lhs] \
1152		 (auto&& __rhs_mem, auto __rhs_index) mutable \
1153		   -> __detail::__variant::__variant_idx_cookie \
1154        { \
1155	  if constexpr (__rhs_index != variant_npos) \
1156	    { \
1157	      if (__lhs.index() == __rhs_index) \
1158	        { \
1159		  auto& __this_mem = std::get<__rhs_index>(__lhs);	\
1160                  __ret = __this_mem __OP __rhs_mem; \
1161                } \
1162	      else \
1163		__ret = (__lhs.index() + 1) __OP (__rhs_index + 1); \
1164            } \
1165          else \
1166            __ret = (__lhs.index() + 1) __OP (__rhs_index + 1); \
1167	  return {}; \
1168	}, __rhs); \
1169      return __ret; \
1170    } \
1171\
1172  constexpr bool operator __OP(monostate, monostate) noexcept \
1173  { return 0 __OP 0; }
1174
1175  _VARIANT_RELATION_FUNCTION_TEMPLATE(<, less)
1176  _VARIANT_RELATION_FUNCTION_TEMPLATE(<=, less_equal)
1177  _VARIANT_RELATION_FUNCTION_TEMPLATE(==, equal)
1178  _VARIANT_RELATION_FUNCTION_TEMPLATE(!=, not_equal)
1179  _VARIANT_RELATION_FUNCTION_TEMPLATE(>=, greater_equal)
1180  _VARIANT_RELATION_FUNCTION_TEMPLATE(>, greater)
1181
1182#undef _VARIANT_RELATION_FUNCTION_TEMPLATE
1183
1184  template<typename _Visitor, typename... _Variants>
1185    constexpr decltype(auto) visit(_Visitor&&, _Variants&&...);
1186
1187  template<typename... _Types>
1188    inline enable_if_t<(is_move_constructible_v<_Types> && ...)
1189			&& (is_swappable_v<_Types> && ...)>
1190    swap(variant<_Types...>& __lhs, variant<_Types...>& __rhs)
1191    noexcept(noexcept(__lhs.swap(__rhs)))
1192    { __lhs.swap(__rhs); }
1193
1194  template<typename... _Types>
1195    enable_if_t<!((is_move_constructible_v<_Types> && ...)
1196		   && (is_swappable_v<_Types> && ...))>
1197    swap(variant<_Types...>&, variant<_Types...>&) = delete;
1198
1199  class bad_variant_access : public exception
1200  {
1201  public:
1202    bad_variant_access() noexcept : _M_reason("Unknown reason") { }
1203    const char* what() const noexcept override
1204    { return _M_reason; }
1205
1206  private:
1207    bad_variant_access(const char* __reason) : _M_reason(__reason) { }
1208
1209    const char* _M_reason;
1210
1211    friend void __throw_bad_variant_access(const char* __what);
1212  };
1213
1214  inline void
1215  __throw_bad_variant_access(const char* __what)
1216  { _GLIBCXX_THROW_OR_ABORT(bad_variant_access(__what)); }
1217
1218  template<typename... _Types>
1219    class variant
1220    : private __detail::__variant::_Variant_base<_Types...>,
1221      private _Enable_default_constructor<
1222	__detail::__variant::_Traits<_Types...>::_S_default_ctor,
1223	  variant<_Types...>>,
1224      private _Enable_copy_move<
1225	__detail::__variant::_Traits<_Types...>::_S_copy_ctor,
1226	__detail::__variant::_Traits<_Types...>::_S_copy_assign,
1227	__detail::__variant::_Traits<_Types...>::_S_move_ctor,
1228	__detail::__variant::_Traits<_Types...>::_S_move_assign,
1229	variant<_Types...>>
1230    {
1231    private:
1232      template <typename... _UTypes, typename _Tp>
1233	friend decltype(auto) __variant_cast(_Tp&&);
1234      template<size_t _Np, typename _Variant, typename... _Args>
1235	friend void __variant_construct_by_index(_Variant& __v,
1236						 _Args&&... __args);
1237
1238      static_assert(sizeof...(_Types) > 0,
1239		    "variant must have at least one alternative");
1240      static_assert(!(std::is_reference_v<_Types> || ...),
1241		    "variant must have no reference alternative");
1242      static_assert(!(std::is_void_v<_Types> || ...),
1243		    "variant must have no void alternative");
1244
1245      using _Base = __detail::__variant::_Variant_base<_Types...>;
1246      using _Default_ctor_enabler =
1247	_Enable_default_constructor<
1248	  __detail::__variant::_Traits<_Types...>::_S_default_ctor,
1249	    variant<_Types...>>;
1250
1251      template<typename _Tp>
1252	static constexpr bool __not_self
1253	  = !is_same_v<__remove_cvref_t<_Tp>, variant>;
1254
1255      template<typename _Tp>
1256	static constexpr bool
1257	__exactly_once = __detail::__variant::__exactly_once<_Tp, _Types...>;
1258
1259      template<typename _Tp>
1260	static constexpr size_t __accepted_index =
1261	  __detail::__variant::__accepted_index<_Tp&&, variant>::value;
1262
1263      template<size_t _Np, typename = enable_if_t<(_Np < sizeof...(_Types))>>
1264	using __to_type = variant_alternative_t<_Np, variant>;
1265
1266      template<typename _Tp, typename = enable_if_t<__not_self<_Tp>>>
1267	using __accepted_type = __to_type<__accepted_index<_Tp>>;
1268
1269      template<typename _Tp>
1270	static constexpr size_t __index_of =
1271	  __detail::__variant::__index_of_v<_Tp, _Types...>;
1272
1273      using _Traits = __detail::__variant::_Traits<_Types...>;
1274
1275      template<typename _Tp>
1276	struct __is_in_place_tag : false_type { };
1277      template<typename _Tp>
1278	struct __is_in_place_tag<in_place_type_t<_Tp>> : true_type { };
1279      template<size_t _Np>
1280	struct __is_in_place_tag<in_place_index_t<_Np>> : true_type { };
1281
1282      template<typename _Tp>
1283	static constexpr bool __not_in_place_tag
1284	  = !__is_in_place_tag<__remove_cvref_t<_Tp>>::value;
1285
1286    public:
1287      variant() = default;
1288      variant(const variant& __rhs) = default;
1289      variant(variant&&) = default;
1290      variant& operator=(const variant&) = default;
1291      variant& operator=(variant&&) = default;
1292      ~variant() = default;
1293
1294      template<typename _Tp,
1295	       typename = enable_if_t<sizeof...(_Types) != 0>,
1296	       typename = enable_if_t<__not_in_place_tag<_Tp>>,
1297	       typename _Tj = __accepted_type<_Tp&&>,
1298	       typename = enable_if_t<__exactly_once<_Tj>
1299				      && is_constructible_v<_Tj, _Tp>>>
1300	constexpr
1301	variant(_Tp&& __t)
1302	noexcept(is_nothrow_constructible_v<_Tj, _Tp>)
1303	: variant(in_place_index<__accepted_index<_Tp&&>>,
1304		  std::forward<_Tp>(__t))
1305	{ }
1306
1307      template<typename _Tp, typename... _Args,
1308	       typename = enable_if_t<__exactly_once<_Tp>
1309				      && is_constructible_v<_Tp, _Args...>>>
1310	constexpr explicit
1311	variant(in_place_type_t<_Tp>, _Args&&... __args)
1312	: variant(in_place_index<__index_of<_Tp>>,
1313		  std::forward<_Args>(__args)...)
1314	{ }
1315
1316      template<typename _Tp, typename _Up, typename... _Args,
1317	       typename = enable_if_t<__exactly_once<_Tp>
1318				      && is_constructible_v<_Tp,
1319					   initializer_list<_Up>&, _Args...>>>
1320	constexpr explicit
1321	variant(in_place_type_t<_Tp>, initializer_list<_Up> __il,
1322		_Args&&... __args)
1323	: variant(in_place_index<__index_of<_Tp>>, __il,
1324		  std::forward<_Args>(__args)...)
1325	{ }
1326
1327      template<size_t _Np, typename... _Args,
1328	       typename _Tp = __to_type<_Np>,
1329	       typename = enable_if_t<is_constructible_v<_Tp, _Args...>>>
1330	constexpr explicit
1331	variant(in_place_index_t<_Np>, _Args&&... __args)
1332	: _Base(in_place_index<_Np>, std::forward<_Args>(__args)...),
1333	_Default_ctor_enabler(_Enable_default_constructor_tag{})
1334	{ }
1335
1336      template<size_t _Np, typename _Up, typename... _Args,
1337	       typename _Tp = __to_type<_Np>,
1338	       typename = enable_if_t<is_constructible_v<_Tp,
1339							 initializer_list<_Up>&,
1340							 _Args...>>>
1341	constexpr explicit
1342	variant(in_place_index_t<_Np>, initializer_list<_Up> __il,
1343		_Args&&... __args)
1344	: _Base(in_place_index<_Np>, __il, std::forward<_Args>(__args)...),
1345	_Default_ctor_enabler(_Enable_default_constructor_tag{})
1346	{ }
1347
1348      template<typename _Tp>
1349	enable_if_t<__exactly_once<__accepted_type<_Tp&&>>
1350		    && is_constructible_v<__accepted_type<_Tp&&>, _Tp>
1351		    && is_assignable_v<__accepted_type<_Tp&&>&, _Tp>,
1352		    variant&>
1353	operator=(_Tp&& __rhs)
1354	noexcept(is_nothrow_assignable_v<__accepted_type<_Tp&&>&, _Tp>
1355		 && is_nothrow_constructible_v<__accepted_type<_Tp&&>, _Tp>)
1356	{
1357	  constexpr auto __index = __accepted_index<_Tp&&>;
1358	  if (index() == __index)
1359	    std::get<__index>(*this) = std::forward<_Tp>(__rhs);
1360	  else
1361	    {
1362	      using _Tj = __accepted_type<_Tp&&>;
1363	      if constexpr (is_nothrow_constructible_v<_Tj, _Tp>
1364			    || !is_nothrow_move_constructible_v<_Tj>)
1365		this->emplace<__index>(std::forward<_Tp>(__rhs));
1366	      else
1367		operator=(variant(std::forward<_Tp>(__rhs)));
1368	    }
1369	  return *this;
1370	}
1371
1372      template<typename _Tp, typename... _Args>
1373	enable_if_t<is_constructible_v<_Tp, _Args...> && __exactly_once<_Tp>,
1374		    _Tp&>
1375	emplace(_Args&&... __args)
1376	{
1377	  constexpr size_t __index = __index_of<_Tp>;
1378	  return this->emplace<__index>(std::forward<_Args>(__args)...);
1379	}
1380
1381      template<typename _Tp, typename _Up, typename... _Args>
1382	enable_if_t<is_constructible_v<_Tp, initializer_list<_Up>&, _Args...>
1383		    && __exactly_once<_Tp>,
1384		    _Tp&>
1385	emplace(initializer_list<_Up> __il, _Args&&... __args)
1386	{
1387	  constexpr size_t __index = __index_of<_Tp>;
1388	  return this->emplace<__index>(__il, std::forward<_Args>(__args)...);
1389	}
1390
1391      template<size_t _Np, typename... _Args>
1392	enable_if_t<is_constructible_v<variant_alternative_t<_Np, variant>,
1393				       _Args...>,
1394		    variant_alternative_t<_Np, variant>&>
1395	emplace(_Args&&... __args)
1396	{
1397	  static_assert(_Np < sizeof...(_Types),
1398			"The index should be in [0, number of alternatives)");
1399	  using type = variant_alternative_t<_Np, variant>;
1400	  // Provide the strong exception-safety guarantee when possible,
1401	  // to avoid becoming valueless.
1402	  if constexpr (is_nothrow_constructible_v<type, _Args...>)
1403	    {
1404	      this->_M_reset();
1405	      __variant_construct_by_index<_Np>(*this,
1406		  std::forward<_Args>(__args)...);
1407	    }
1408	  else if constexpr (is_scalar_v<type>)
1409	    {
1410	      // This might invoke a potentially-throwing conversion operator:
1411	      const type __tmp(std::forward<_Args>(__args)...);
1412	      // But these steps won't throw:
1413	      this->_M_reset();
1414	      __variant_construct_by_index<_Np>(*this, __tmp);
1415	    }
1416	  else if constexpr (__detail::__variant::_Never_valueless_alt<type>()
1417	      && _Traits::_S_move_assign)
1418	    {
1419	      // This construction might throw:
1420	      variant __tmp(in_place_index<_Np>,
1421			    std::forward<_Args>(__args)...);
1422	      // But _Never_valueless_alt<type> means this won't:
1423	      *this = std::move(__tmp);
1424	    }
1425	  else
1426	    {
1427	      // This case only provides the basic exception-safety guarantee,
1428	      // i.e. the variant can become valueless.
1429	      this->_M_reset();
1430	      __try
1431		{
1432		  __variant_construct_by_index<_Np>(*this,
1433		    std::forward<_Args>(__args)...);
1434		}
1435	      __catch (...)
1436		{
1437		  this->_M_index = variant_npos;
1438		  __throw_exception_again;
1439		}
1440	    }
1441	  return std::get<_Np>(*this);
1442	}
1443
1444      template<size_t _Np, typename _Up, typename... _Args>
1445	enable_if_t<is_constructible_v<variant_alternative_t<_Np, variant>,
1446				       initializer_list<_Up>&, _Args...>,
1447		    variant_alternative_t<_Np, variant>&>
1448	emplace(initializer_list<_Up> __il, _Args&&... __args)
1449	{
1450	  static_assert(_Np < sizeof...(_Types),
1451			"The index should be in [0, number of alternatives)");
1452	  using type = variant_alternative_t<_Np, variant>;
1453	  // Provide the strong exception-safety guarantee when possible,
1454	  // to avoid becoming valueless.
1455	  if constexpr (is_nothrow_constructible_v<type,
1456						   initializer_list<_Up>&,
1457						   _Args...>)
1458	    {
1459	      this->_M_reset();
1460	      __variant_construct_by_index<_Np>(*this, __il,
1461		  std::forward<_Args>(__args)...);
1462	    }
1463	  else if constexpr (__detail::__variant::_Never_valueless_alt<type>()
1464	      && _Traits::_S_move_assign)
1465	    {
1466	      // This construction might throw:
1467	      variant __tmp(in_place_index<_Np>, __il,
1468			    std::forward<_Args>(__args)...);
1469	      // But _Never_valueless_alt<type> means this won't:
1470	      *this = std::move(__tmp);
1471	    }
1472	  else
1473	    {
1474	      // This case only provides the basic exception-safety guarantee,
1475	      // i.e. the variant can become valueless.
1476	      this->_M_reset();
1477	      __try
1478		{
1479		  __variant_construct_by_index<_Np>(*this, __il,
1480		    std::forward<_Args>(__args)...);
1481		}
1482	      __catch (...)
1483		{
1484		  this->_M_index = variant_npos;
1485		  __throw_exception_again;
1486		}
1487	    }
1488	  return std::get<_Np>(*this);
1489	}
1490
1491      constexpr bool valueless_by_exception() const noexcept
1492      { return !this->_M_valid(); }
1493
1494      constexpr size_t index() const noexcept
1495      {
1496	if (this->_M_index ==
1497	    typename _Base::__index_type(variant_npos))
1498	  return variant_npos;
1499	return this->_M_index;
1500      }
1501
1502      void
1503      swap(variant& __rhs)
1504      noexcept((__is_nothrow_swappable<_Types>::value && ...)
1505	       && is_nothrow_move_constructible_v<variant>)
1506      {
1507	__do_visit<__detail::__variant::__visit_with_index>(
1508	  [this, &__rhs](auto&& __rhs_mem,
1509			 auto __rhs_index) mutable
1510	    -> __detail::__variant::__variant_idx_cookie
1511	  {
1512	    if constexpr (__rhs_index != variant_npos)
1513	      {
1514		if (this->index() == __rhs_index)
1515		  {
1516		    auto& __this_mem =
1517		      std::get<__rhs_index>(*this);
1518		    using std::swap;
1519		    swap(__this_mem, __rhs_mem);
1520		  }
1521		else
1522		  {
1523		    if (this->index() != variant_npos)
1524		      {
1525			auto __tmp(std::move(__rhs_mem));
1526			__rhs = std::move(*this);
1527			this->_M_destructive_move(__rhs_index,
1528						  std::move(__tmp));
1529		      }
1530		    else
1531		      {
1532			this->_M_destructive_move(__rhs_index,
1533						  std::move(__rhs_mem));
1534			__rhs._M_reset();
1535		      }
1536		  }
1537	      }
1538	    else
1539	      {
1540		if (this->index() != variant_npos)
1541		  {
1542		    __rhs = std::move(*this);
1543		    this->_M_reset();
1544		  }
1545	      }
1546	    return {};
1547	  }, __rhs);
1548      }
1549
1550    private:
1551
1552#if defined(__clang__) && __clang_major__ <= 7
1553    public:
1554      using _Base::_M_u; // See https://bugs.llvm.org/show_bug.cgi?id=31852
1555    private:
1556#endif
1557
1558      template<size_t _Np, typename _Vp>
1559	friend constexpr decltype(auto)
1560	__detail::__variant::__get(_Vp&& __v) noexcept;
1561
1562      template<typename _Vp>
1563	friend void* __detail::__variant::__get_storage(_Vp&& __v);
1564
1565#define _VARIANT_RELATION_FUNCTION_TEMPLATE(__OP) \
1566      template<typename... _Tp> \
1567	friend constexpr bool \
1568	operator __OP(const variant<_Tp...>& __lhs, \
1569		      const variant<_Tp...>& __rhs);
1570
1571      _VARIANT_RELATION_FUNCTION_TEMPLATE(<)
1572      _VARIANT_RELATION_FUNCTION_TEMPLATE(<=)
1573      _VARIANT_RELATION_FUNCTION_TEMPLATE(==)
1574      _VARIANT_RELATION_FUNCTION_TEMPLATE(!=)
1575      _VARIANT_RELATION_FUNCTION_TEMPLATE(>=)
1576      _VARIANT_RELATION_FUNCTION_TEMPLATE(>)
1577
1578#undef _VARIANT_RELATION_FUNCTION_TEMPLATE
1579    };
1580
1581  template<size_t _Np, typename... _Types>
1582    constexpr variant_alternative_t<_Np, variant<_Types...>>&
1583    get(variant<_Types...>& __v)
1584    {
1585      static_assert(_Np < sizeof...(_Types),
1586		    "The index should be in [0, number of alternatives)");
1587      if (__v.index() != _Np)
1588	__throw_bad_variant_access("Unexpected index");
1589      return __detail::__variant::__get<_Np>(__v);
1590    }
1591
1592  template<size_t _Np, typename... _Types>
1593    constexpr variant_alternative_t<_Np, variant<_Types...>>&&
1594    get(variant<_Types...>&& __v)
1595    {
1596      static_assert(_Np < sizeof...(_Types),
1597		    "The index should be in [0, number of alternatives)");
1598      if (__v.index() != _Np)
1599	__throw_bad_variant_access("Unexpected index");
1600      return __detail::__variant::__get<_Np>(std::move(__v));
1601    }
1602
1603  template<size_t _Np, typename... _Types>
1604    constexpr const variant_alternative_t<_Np, variant<_Types...>>&
1605    get(const variant<_Types...>& __v)
1606    {
1607      static_assert(_Np < sizeof...(_Types),
1608		    "The index should be in [0, number of alternatives)");
1609      if (__v.index() != _Np)
1610	__throw_bad_variant_access("Unexpected index");
1611      return __detail::__variant::__get<_Np>(__v);
1612    }
1613
1614  template<size_t _Np, typename... _Types>
1615    constexpr const variant_alternative_t<_Np, variant<_Types...>>&&
1616    get(const variant<_Types...>&& __v)
1617    {
1618      static_assert(_Np < sizeof...(_Types),
1619		    "The index should be in [0, number of alternatives)");
1620      if (__v.index() != _Np)
1621	__throw_bad_variant_access("Unexpected index");
1622      return __detail::__variant::__get<_Np>(std::move(__v));
1623    }
1624
1625  template<bool __use_index,
1626	   bool __same_return_types,
1627	   typename _Visitor, typename... _Variants>
1628    constexpr decltype(auto)
1629    __do_visit(_Visitor&& __visitor, _Variants&&... __variants)
1630    {
1631      using _Deduced_type = std::invoke_result<_Visitor,
1632	decltype(std::get<0>(std::declval<_Variants>()))...>;
1633
1634      using _Result_type = typename std::conditional_t<__use_index,
1635	__detail::__variant::__variant_idx_cookie,
1636	_Deduced_type>::type;
1637
1638      constexpr auto& __vtable = __detail::__variant::__gen_vtable<
1639	__same_return_types,
1640	_Result_type, _Visitor&&, _Variants&&...>::_S_vtable;
1641
1642      auto __func_ptr = __vtable._M_access(__variants.index()...);
1643      return (*__func_ptr)(std::forward<_Visitor>(__visitor),
1644			   std::forward<_Variants>(__variants)...);
1645    }
1646
1647  template<typename _Visitor, typename... _Variants>
1648    constexpr decltype(auto)
1649    visit(_Visitor&& __visitor, _Variants&&... __variants)
1650    {
1651      if ((__variants.valueless_by_exception() || ...))
1652	__throw_bad_variant_access("Unexpected index");
1653
1654      return __do_visit(std::forward<_Visitor>(__visitor),
1655			std::forward<_Variants>(__variants)...);
1656    }
1657
1658#if __cplusplus > 201703L
1659  template<typename _Res, typename _Visitor, typename... _Variants>
1660    constexpr _Res
1661    visit(_Visitor&& __visitor, _Variants&&... __variants)
1662    {
1663      if ((__variants.valueless_by_exception() || ...))
1664	__throw_bad_variant_access("Unexpected index");
1665
1666      if constexpr (std::is_void_v<_Res>)
1667        (void) __do_visit<false, false>(std::forward<_Visitor>(__visitor),
1668					std::forward<_Variants>(__variants)...);
1669      else
1670	return __do_visit<false, false>(std::forward<_Visitor>(__visitor),
1671					std::forward<_Variants>(__variants)...);
1672    }
1673#endif
1674
1675  template<bool, typename... _Types>
1676    struct __variant_hash_call_base_impl
1677    {
1678      size_t
1679      operator()(const variant<_Types...>& __t) const
1680      noexcept((is_nothrow_invocable_v<hash<decay_t<_Types>>, _Types> && ...))
1681      {
1682	size_t __ret;
1683	__do_visit([&__t, &__ret](auto&& __t_mem) mutable
1684		   -> __detail::__variant::__variant_cookie
1685	  {
1686	    using _Type = __remove_cvref_t<decltype(__t_mem)>;
1687	    if constexpr (!is_same_v<_Type,
1688			             __detail::__variant::__variant_cookie>)
1689	      __ret = std::hash<size_t>{}(__t.index())
1690		      + std::hash<_Type>{}(__t_mem);
1691	    else
1692	      __ret = std::hash<size_t>{}(__t.index());
1693	    return {};
1694	  }, __t);
1695	return __ret;
1696      }
1697    };
1698
1699  template<typename... _Types>
1700    struct __variant_hash_call_base_impl<false, _Types...> {};
1701
1702  template<typename... _Types>
1703    using __variant_hash_call_base =
1704    __variant_hash_call_base_impl<(__poison_hash<remove_const_t<_Types>>::
1705				   __enable_hash_call &&...), _Types...>;
1706
1707  template<typename... _Types>
1708    struct hash<variant<_Types...>>
1709    : private __detail::__variant::_Variant_hash_base<
1710	variant<_Types...>, std::index_sequence_for<_Types...>>,
1711      public __variant_hash_call_base<_Types...>
1712    {
1713      using result_type [[__deprecated__]] = size_t;
1714      using argument_type [[__deprecated__]] = variant<_Types...>;
1715    };
1716
1717  template<>
1718    struct hash<monostate>
1719    {
1720      using result_type [[__deprecated__]] = size_t;
1721      using argument_type [[__deprecated__]] = monostate;
1722
1723      size_t
1724      operator()(const monostate& __t) const noexcept
1725      {
1726	constexpr size_t __magic_monostate_hash = -7777;
1727	return __magic_monostate_hash;
1728      }
1729    };
1730
1731  template<typename... _Types>
1732    struct __is_fast_hash<hash<variant<_Types...>>>
1733    : bool_constant<(__is_fast_hash<_Types>::value && ...)>
1734    { };
1735
1736_GLIBCXX_END_NAMESPACE_VERSION
1737} // namespace std
1738
1739#endif // C++17
1740
1741#endif // _GLIBCXX_VARIANT
1742