variant.h 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846
  1. // Copyright 2018 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. // -----------------------------------------------------------------------------
  16. // variant.h
  17. // -----------------------------------------------------------------------------
  18. //
  19. // This header file defines an `absl::variant` type for holding a type-safe
  20. // value of some prescribed set of types (noted as alternative types), and
  21. // associated functions for managing variants.
  22. //
  23. // The `absl::variant` type is a form of type-safe union. An `absl::variant`
  24. // should always hold a value of one of its alternative types (except in the
  25. // "valueless by exception state" -- see below). A default-constructed
  26. // `absl::variant` will hold the value of its first alternative type, provided
  27. // it is default-constructable.
  28. //
  29. // In exceptional cases due to error, an `absl::variant` can hold no
  30. // value (known as a "valueless by exception" state), though this is not the
  31. // norm.
  32. //
  33. // As with `absl::optional`, an `absl::variant` -- when it holds a value --
  34. // allocates a value of that type directly within the `variant` itself; it
  35. // cannot hold a reference, array, or the type `void`; it can, however, hold a
  36. // pointer to externally managed memory.
  37. //
  38. // `absl::variant` is a C++11 compatible version of the C++17 `std::variant`
  39. // abstraction and is designed to be a drop-in replacement for code compliant
  40. // with C++17.
  41. #ifndef ABSL_TYPES_VARIANT_H_
  42. #define ABSL_TYPES_VARIANT_H_
  43. #include "absl/base/config.h"
  44. #include "absl/utility/utility.h"
  45. #ifdef ABSL_HAVE_STD_VARIANT
  46. #include <variant>
  47. namespace absl {
  48. inline namespace lts_2018_06_20 {
  49. using std::bad_variant_access;
  50. using std::get;
  51. using std::get_if;
  52. using std::holds_alternative;
  53. using std::monostate;
  54. using std::variant;
  55. using std::variant_alternative;
  56. using std::variant_alternative_t;
  57. using std::variant_npos;
  58. using std::variant_size;
  59. using std::variant_size_v;
  60. using std::visit;
  61. } // inline namespace lts_2018_06_20
  62. } // namespace absl
  63. #else // ABSL_HAVE_STD_VARIANT
  64. #include <functional>
  65. #include <new>
  66. #include <type_traits>
  67. #include <utility>
  68. #include "absl/base/macros.h"
  69. #include "absl/base/port.h"
  70. #include "absl/meta/type_traits.h"
  71. #include "absl/types/internal/variant.h"
  72. namespace absl {
  73. inline namespace lts_2018_06_20 {
  74. // -----------------------------------------------------------------------------
  75. // absl::variant
  76. // -----------------------------------------------------------------------------
  77. //
  78. // An 'absl::variant` type is a form of type-safe union. An `absl::variant` --
  79. // except in exceptional cases -- always holds a value of one of its alternative
  80. // types.
  81. //
  82. // Example:
  83. //
  84. // // Construct a variant that holds either an integer or a std::string and
  85. // // assign it to a std::string.
  86. // absl::variant<int, std::string> v = std::string("abc");
  87. //
  88. // // A default-contructed variant will hold a value-initialized value of
  89. // // the first alternative type.
  90. // auto a = absl::variant<int, std::string>(); // Holds an int of value '0'.
  91. //
  92. // // variants are assignable.
  93. //
  94. // // copy assignment
  95. // auto v1 = absl::variant<int, std::string>("abc");
  96. // auto v2 = absl::variant<int, std::string>(10);
  97. // v2 = v1; // copy assign
  98. //
  99. // // move assignment
  100. // auto v1 = absl::variant<int, std::string>("abc");
  101. // v1 = absl::variant<int, std::string>(10);
  102. //
  103. // // assignment through type conversion
  104. // a = 128; // variant contains int
  105. // a = "128"; // variant contains std::string
  106. //
  107. // An `absl::variant` holding a value of one of its alternative types `T` holds
  108. // an allocation of `T` directly within the variant itself. An `absl::variant`
  109. // is not allowed to allocate additional storage, such as dynamic memory, to
  110. // allocate the contained value. The contained value shall be allocated in a
  111. // region of the variant storage suitably aligned for all alternative types.
  112. template <typename... Ts>
  113. class variant;
  114. // swap()
  115. //
  116. // Swaps two `absl::variant` values. This function is equivalent to `v.swap(w)`
  117. // where `v` and `w` are `absl::variant` types.
  118. //
  119. // Note that this function requires all alternative types to be both swappable
  120. // and move-constructible, because any two variants may refer to either the same
  121. // type (in which case, they will be swapped) or to two different types (in
  122. // which case the values will need to be moved).
  123. //
  124. template <typename... Ts>
  125. void swap(variant<Ts...>& v, variant<Ts...>& w) noexcept(noexcept(v.swap(w))) {
  126. v.swap(w);
  127. }
  128. // variant_size
  129. //
  130. // Returns the number of alterative types available for a given `absl::variant`
  131. // type as a compile-time constant expression. As this is a class template, it
  132. // is not generally useful for accessing the number of alternative types of
  133. // any given `absl::variant` instance.
  134. //
  135. // Example:
  136. //
  137. // auto a = absl::variant<int, std::string>;
  138. // constexpr int num_types =
  139. // absl::variant_size<absl::variant<int, std::string>>();
  140. //
  141. // // You can also use the member constant `value`.
  142. // constexpr int num_types =
  143. // absl::variant_size<absl::variant<int, std::string>>::value;
  144. //
  145. // // `absl::variant_size` is more valuable for use in generic code:
  146. // template <typename Variant>
  147. // constexpr bool IsVariantMultivalue() {
  148. // return absl::variant_size<Variant>() > 1;
  149. // }
  150. //
  151. // Note that the set of cv-qualified specializations of `variant_size` are
  152. // provided to ensure that those specializations compile (especially when passed
  153. // within template logic).
  154. template <class T>
  155. struct variant_size;
  156. template <class... Ts>
  157. struct variant_size<variant<Ts...>>
  158. : std::integral_constant<std::size_t, sizeof...(Ts)> {};
  159. // Specialization of `variant_size` for const qualified variants.
  160. template <class T>
  161. struct variant_size<const T> : variant_size<T>::type {};
  162. // Specialization of `variant_size` for volatile qualified variants.
  163. template <class T>
  164. struct variant_size<volatile T> : variant_size<T>::type {};
  165. // Specialization of `variant_size` for const volatile qualified variants.
  166. template <class T>
  167. struct variant_size<const volatile T> : variant_size<T>::type {};
  168. // variant_alternative
  169. //
  170. // Returns the alternative type for a given `absl::variant` at the passed
  171. // index value as a compile-time constant expression. As this is a class
  172. // template resulting in a type, it is not useful for access of the run-time
  173. // value of any given `absl::variant` variable.
  174. //
  175. // Example:
  176. //
  177. // // The type of the 0th alternative is "int".
  178. // using alternative_type_0
  179. // = absl::variant_alternative<0, absl::variant<int, std::string>>::type;
  180. //
  181. // static_assert(std::is_same<alternative_type_0, int>::value, "");
  182. //
  183. // // `absl::variant_alternative` is more valuable for use in generic code:
  184. // template <typename Variant>
  185. // constexpr bool IsFirstElementTrivial() {
  186. // return std::is_trivial_v<variant_alternative<0, Variant>::type>;
  187. // }
  188. //
  189. // Note that the set of cv-qualified specializations of `variant_alternative`
  190. // are provided to ensure that those specializations compile (especially when
  191. // passed within template logic).
  192. template <std::size_t I, class T>
  193. struct variant_alternative;
  194. template <std::size_t I, class... Types>
  195. struct variant_alternative<I, variant<Types...>> {
  196. using type =
  197. variant_internal::VariantAlternativeSfinaeT<I, variant<Types...>>;
  198. };
  199. // Specialization of `variant_alternative` for const qualified variants.
  200. template <std::size_t I, class T>
  201. struct variant_alternative<I, const T> {
  202. using type = const typename variant_alternative<I, T>::type;
  203. };
  204. // Specialization of `variant_alternative` for volatile qualified variants.
  205. template <std::size_t I, class T>
  206. struct variant_alternative<I, volatile T> {
  207. using type = volatile typename variant_alternative<I, T>::type;
  208. };
  209. // Specialization of `variant_alternative` for const volatile qualified
  210. // variants.
  211. template <std::size_t I, class T>
  212. struct variant_alternative<I, const volatile T> {
  213. using type = const volatile typename variant_alternative<I, T>::type;
  214. };
  215. // Template type alias for variant_alternative<I, T>::type.
  216. //
  217. // Example:
  218. //
  219. // using alternative_type_0
  220. // = absl::variant_alternative_t<0, absl::variant<int, std::string>>;
  221. // static_assert(std::is_same<alternative_type_0, int>::value, "");
  222. template <std::size_t I, class T>
  223. using variant_alternative_t = typename variant_alternative<I, T>::type;
  224. // holds_alternative()
  225. //
  226. // Checks whether the given variant currently holds a given alternative type,
  227. // returning `true` if so.
  228. //
  229. // Example:
  230. //
  231. // absl::variant<int, std::string> bar = 42;
  232. // if (absl::holds_alternative<int>(foo)) {
  233. // std::cout << "The variant holds an integer";
  234. // }
  235. template <class T, class... Types>
  236. constexpr bool holds_alternative(const variant<Types...>& v) noexcept {
  237. static_assert(
  238. variant_internal::UnambiguousIndexOfImpl<variant<Types...>, T,
  239. 0>::value != sizeof...(Types),
  240. "The type T must occur exactly once in Types...");
  241. return v.index() ==
  242. variant_internal::UnambiguousIndexOf<variant<Types...>, T>::value;
  243. }
  244. // get()
  245. //
  246. // Returns a reference to the value currently within a given variant, using
  247. // either a unique alternative type amongst the variant's set of alternative
  248. // types, or the variant's index value. Attempting to get a variant's value
  249. // using a type that is not unique within the variant's set of alternative types
  250. // is a compile-time error. If the index of the alternative being specified is
  251. // different from the index of the alternative that is currently stored, throws
  252. // `absl::bad_variant_access`.
  253. //
  254. // Example:
  255. //
  256. // auto a = absl::variant<int, std::string>;
  257. //
  258. // // Get the value by type (if unique).
  259. // int i = absl::get<int>(a);
  260. //
  261. // auto b = absl::variant<int, int>;
  262. //
  263. // // Getting the value by a type that is not unique is ill-formed.
  264. // int j = absl::get<int>(b); // Compile Error!
  265. //
  266. // // Getting value by index not ambiguous and allowed.
  267. // int k = absl::get<1>(b);
  268. // Overload for getting a variant's lvalue by type.
  269. template <class T, class... Types>
  270. constexpr T& get(variant<Types...>& v) { // NOLINT
  271. return variant_internal::VariantCoreAccess::Access<
  272. variant_internal::IndexOf<T, Types...>::value>(v);
  273. }
  274. // Overload for getting a variant's rvalue by type.
  275. // Note: `absl::move()` is required to allow use of constexpr in C++11.
  276. template <class T, class... Types>
  277. constexpr T&& get(variant<Types...>&& v) {
  278. return variant_internal::VariantCoreAccess::Access<
  279. variant_internal::IndexOf<T, Types...>::value>(absl::move(v));
  280. }
  281. // Overload for getting a variant's const lvalue by type.
  282. template <class T, class... Types>
  283. constexpr const T& get(const variant<Types...>& v) {
  284. return variant_internal::VariantCoreAccess::Access<
  285. variant_internal::IndexOf<T, Types...>::value>(v);
  286. }
  287. // Overload for getting a variant's const rvalue by type.
  288. // Note: `absl::move()` is required to allow use of constexpr in C++11.
  289. template <class T, class... Types>
  290. constexpr const T&& get(const variant<Types...>&& v) {
  291. return variant_internal::VariantCoreAccess::Access<
  292. variant_internal::IndexOf<T, Types...>::value>(absl::move(v));
  293. }
  294. // Overload for getting a variant's lvalue by index.
  295. template <std::size_t I, class... Types>
  296. constexpr variant_alternative_t<I, variant<Types...>>& get(
  297. variant<Types...>& v) { // NOLINT
  298. return variant_internal::VariantCoreAccess::Access<I>(v);
  299. }
  300. // Overload for getting a variant's rvalue by index.
  301. // Note: `absl::move()` is required to allow use of constexpr in C++11.
  302. template <std::size_t I, class... Types>
  303. constexpr variant_alternative_t<I, variant<Types...>>&& get(
  304. variant<Types...>&& v) {
  305. return variant_internal::VariantCoreAccess::Access<I>(absl::move(v));
  306. }
  307. // Overload for getting a variant's const lvalue by index.
  308. template <std::size_t I, class... Types>
  309. constexpr const variant_alternative_t<I, variant<Types...>>& get(
  310. const variant<Types...>& v) {
  311. return variant_internal::VariantCoreAccess::Access<I>(v);
  312. }
  313. // Overload for getting a variant's const rvalue by index.
  314. // Note: `absl::move()` is required to allow use of constexpr in C++11.
  315. template <std::size_t I, class... Types>
  316. constexpr const variant_alternative_t<I, variant<Types...>>&& get(
  317. const variant<Types...>&& v) {
  318. return variant_internal::VariantCoreAccess::Access<I>(absl::move(v));
  319. }
  320. // get_if()
  321. //
  322. // Returns a pointer to the value currently stored within a given variant, if
  323. // present, using either a unique alternative type amongst the variant's set of
  324. // alternative types, or the variant's index value. If such a value does not
  325. // exist, returns `nullptr`.
  326. //
  327. // As with `get`, attempting to get a variant's value using a type that is not
  328. // unique within the variant's set of alternative types is a compile-time error.
  329. // Overload for getting a pointer to the value stored in the given variant by
  330. // index.
  331. template <std::size_t I, class... Types>
  332. constexpr absl::add_pointer_t<variant_alternative_t<I, variant<Types...>>>
  333. get_if(variant<Types...>* v) noexcept {
  334. return (v != nullptr && v->index() == I) ? std::addressof(absl::get<I>(*v))
  335. : nullptr;
  336. }
  337. // Overload for getting a pointer to the const value stored in the given
  338. // variant by index.
  339. template <std::size_t I, class... Types>
  340. constexpr absl::add_pointer_t<const variant_alternative_t<I, variant<Types...>>>
  341. get_if(const variant<Types...>* v) noexcept {
  342. return (v != nullptr && v->index() == I) ? std::addressof(absl::get<I>(*v))
  343. : nullptr;
  344. }
  345. // Overload for getting a pointer to the value stored in the given variant by
  346. // type.
  347. template <class T, class... Types>
  348. constexpr absl::add_pointer_t<T> get_if(variant<Types...>* v) noexcept {
  349. return absl::get_if<variant_internal::IndexOf<T, Types...>::value>(v);
  350. }
  351. // Overload for getting a pointer to the const value stored in the given variant
  352. // by type.
  353. template <class T, class... Types>
  354. constexpr absl::add_pointer_t<const T> get_if(
  355. const variant<Types...>* v) noexcept {
  356. return absl::get_if<variant_internal::IndexOf<T, Types...>::value>(v);
  357. }
  358. // visit()
  359. //
  360. // Calls a provided functor on a given set of variants. `absl::visit()` is
  361. // commonly used to conditionally inspect the state of a given variant (or set
  362. // of variants).
  363. // Requires: The expression in the Effects: element shall be a valid expression
  364. // of the same type and value category, for all combinations of alternative
  365. // types of all variants. Otherwise, the program is ill-formed.
  366. //
  367. // Example:
  368. //
  369. // // Define a visitor functor
  370. // struct GetVariant {
  371. // template<typename T>
  372. // void operator()(const T& i) const {
  373. // std::cout << "The variant's value is: " << i;
  374. // }
  375. // };
  376. //
  377. // // Declare our variant, and call `absl::visit()` on it.
  378. // std::variant<int, std::string> foo = std::string("foo");
  379. // GetVariant visitor;
  380. // std::visit(visitor, foo); // Prints `The variant's value is: foo'
  381. template <typename Visitor, typename... Variants>
  382. variant_internal::VisitResult<Visitor, Variants...> visit(Visitor&& vis,
  383. Variants&&... vars) {
  384. return variant_internal::
  385. VisitIndices<variant_size<absl::decay_t<Variants> >::value...>::Run(
  386. variant_internal::PerformVisitation<Visitor, Variants...>{
  387. std::forward_as_tuple(absl::forward<Variants>(vars)...),
  388. absl::forward<Visitor>(vis)},
  389. vars.index()...);
  390. }
  391. // monostate
  392. //
  393. // The monostate class serves as a first alternative type for a variant for
  394. // which the first variant type is otherwise not default-constructible.
  395. struct monostate {};
  396. // `absl::monostate` Relational Operators
  397. constexpr bool operator<(monostate, monostate) noexcept { return false; }
  398. constexpr bool operator>(monostate, monostate) noexcept { return false; }
  399. constexpr bool operator<=(monostate, monostate) noexcept { return true; }
  400. constexpr bool operator>=(monostate, monostate) noexcept { return true; }
  401. constexpr bool operator==(monostate, monostate) noexcept { return true; }
  402. constexpr bool operator!=(monostate, monostate) noexcept { return false; }
  403. //------------------------------------------------------------------------------
  404. // `absl::variant` Template Definition
  405. //------------------------------------------------------------------------------
  406. template <typename T0, typename... Tn>
  407. class variant<T0, Tn...> : private variant_internal::VariantBase<T0, Tn...> {
  408. // Intentionally not qualifing `negation` with `absl::` to work around a bug
  409. // in MSVC 2015 with inline namespace and variadic template.
  410. static_assert(absl::conjunction<std::is_object<T0>, std::is_object<Tn>...,
  411. negation<std::is_array<T0> >,
  412. negation<std::is_array<Tn> >...,
  413. std::is_nothrow_destructible<T0>,
  414. std::is_nothrow_destructible<Tn>...>::value,
  415. "Attempted to instantiate a variant with an unsupported type.");
  416. friend struct variant_internal::VariantCoreAccess;
  417. private:
  418. using Base = variant_internal::VariantBase<T0, Tn...>;
  419. public:
  420. // Constructors
  421. // Constructs a variant holding a default-initialized value of the first
  422. // alternative type.
  423. constexpr variant() /*noexcept(see 111above)*/ = default;
  424. // Copy constructor, standard semantics
  425. variant(const variant& other) = default;
  426. // Move constructor, standard semantics
  427. variant(variant&& other) /*noexcept(see above)*/ = default;
  428. // Constructs a variant of an alternative type specified by overload
  429. // resolution of the provided forwarding arguments through
  430. // direct-initialization.
  431. //
  432. // Note: If the selected constructor is a constexpr constructor, this
  433. // constructor shall be a constexpr constructor.
  434. //
  435. // NOTE: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p0608r1.html
  436. // has been voted passed the design phase in the C++ standard meeting in Mar
  437. // 2018. It will be implemented and integrated into `absl::variant`.
  438. template <
  439. class T,
  440. std::size_t I = std::enable_if<
  441. variant_internal::IsNeitherSelfNorInPlace<variant,
  442. absl::decay_t<T>>::value,
  443. variant_internal::IndexOfConstructedType<variant, T>>::type::value,
  444. class Tj = absl::variant_alternative_t<I, variant>,
  445. absl::enable_if_t<std::is_constructible<Tj, T>::value>* =
  446. nullptr>
  447. constexpr variant(T&& t) noexcept(std::is_nothrow_constructible<Tj, T>::value)
  448. : Base(variant_internal::EmplaceTag<I>(), absl::forward<T>(t)) {}
  449. // Constructs a variant of an alternative type from the arguments through
  450. // direct-initialization.
  451. //
  452. // Note: If the selected constructor is a constexpr constructor, this
  453. // constructor shall be a constexpr constructor.
  454. template <class T, class... Args,
  455. typename std::enable_if<std::is_constructible<
  456. variant_internal::UnambiguousTypeOfT<variant, T>,
  457. Args...>::value>::type* = nullptr>
  458. constexpr explicit variant(in_place_type_t<T>, Args&&... args)
  459. : Base(variant_internal::EmplaceTag<
  460. variant_internal::UnambiguousIndexOf<variant, T>::value>(),
  461. absl::forward<Args>(args)...) {}
  462. // Constructs a variant of an alternative type from an initializer list
  463. // and other arguments through direct-initialization.
  464. //
  465. // Note: If the selected constructor is a constexpr constructor, this
  466. // constructor shall be a constexpr constructor.
  467. template <class T, class U, class... Args,
  468. typename std::enable_if<std::is_constructible<
  469. variant_internal::UnambiguousTypeOfT<variant, T>,
  470. std::initializer_list<U>&, Args...>::value>::type* = nullptr>
  471. constexpr explicit variant(in_place_type_t<T>, std::initializer_list<U> il,
  472. Args&&... args)
  473. : Base(variant_internal::EmplaceTag<
  474. variant_internal::UnambiguousIndexOf<variant, T>::value>(),
  475. il, absl::forward<Args>(args)...) {}
  476. // Constructs a variant of an alternative type from a provided index,
  477. // through value-initialization using the provided forwarded arguments.
  478. template <std::size_t I, class... Args,
  479. typename std::enable_if<std::is_constructible<
  480. variant_internal::VariantAlternativeSfinaeT<I, variant>,
  481. Args...>::value>::type* = nullptr>
  482. constexpr explicit variant(in_place_index_t<I>, Args&&... args)
  483. : Base(variant_internal::EmplaceTag<I>(), absl::forward<Args>(args)...) {}
  484. // Constructs a variant of an alternative type from a provided index,
  485. // through value-initialization of an initializer list and the provided
  486. // forwarded arguments.
  487. template <std::size_t I, class U, class... Args,
  488. typename std::enable_if<std::is_constructible<
  489. variant_internal::VariantAlternativeSfinaeT<I, variant>,
  490. std::initializer_list<U>&, Args...>::value>::type* = nullptr>
  491. constexpr explicit variant(in_place_index_t<I>, std::initializer_list<U> il,
  492. Args&&... args)
  493. : Base(variant_internal::EmplaceTag<I>(), il,
  494. absl::forward<Args>(args)...) {}
  495. // Destructors
  496. // Destroys the variant's currently contained value, provided that
  497. // `absl::valueless_by_exception()` is false.
  498. ~variant() = default;
  499. // Assignment Operators
  500. // Copy assignement operator
  501. variant& operator=(const variant& other) = default;
  502. // Move assignment operator
  503. variant& operator=(variant&& other) /*noexcept(see above)*/ = default;
  504. // Converting assignment operator
  505. //
  506. // NOTE: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p0608r1.html
  507. // has been voted passed the design phase in the C++ standard meeting in Mar
  508. // 2018. It will be implemented and integrated into `absl::variant`.
  509. template <
  510. class T,
  511. std::size_t I = std::enable_if<
  512. !std::is_same<absl::decay_t<T>, variant>::value,
  513. variant_internal::IndexOfConstructedType<variant, T>>::type::value,
  514. class Tj = absl::variant_alternative_t<I, variant>,
  515. typename std::enable_if<std::is_assignable<Tj&, T>::value &&
  516. std::is_constructible<Tj, T>::value>::type* =
  517. nullptr>
  518. variant& operator=(T&& t) noexcept(
  519. std::is_nothrow_assignable<Tj&, T>::value&&
  520. std::is_nothrow_constructible<Tj, T>::value) {
  521. variant_internal::VisitIndices<sizeof...(Tn) + 1>::Run(
  522. variant_internal::VariantCoreAccess::MakeConversionAssignVisitor(
  523. this, absl::forward<T>(t)),
  524. index());
  525. return *this;
  526. }
  527. // emplace() Functions
  528. // Constructs a value of the given alternative type T within the variant.
  529. //
  530. // Example:
  531. //
  532. // absl::variant<std::vector<int>, int, std::string> v;
  533. // v.emplace<int>(99);
  534. // v.emplace<std::string>("abc");
  535. template <
  536. class T, class... Args,
  537. typename std::enable_if<std::is_constructible<
  538. absl::variant_alternative_t<
  539. variant_internal::UnambiguousIndexOf<variant, T>::value, variant>,
  540. Args...>::value>::type* = nullptr>
  541. T& emplace(Args&&... args) {
  542. return variant_internal::VariantCoreAccess::Replace<
  543. variant_internal::UnambiguousIndexOf<variant, T>::value>(
  544. this, absl::forward<Args>(args)...);
  545. }
  546. // Constructs a value of the given alternative type T within the variant using
  547. // an initializer list.
  548. //
  549. // Example:
  550. //
  551. // absl::variant<std::vector<int>, int, std::string> v;
  552. // v.emplace<std::vector<int>>({0, 1, 2});
  553. template <
  554. class T, class U, class... Args,
  555. typename std::enable_if<std::is_constructible<
  556. absl::variant_alternative_t<
  557. variant_internal::UnambiguousIndexOf<variant, T>::value, variant>,
  558. std::initializer_list<U>&, Args...>::value>::type* = nullptr>
  559. T& emplace(std::initializer_list<U> il, Args&&... args) {
  560. return variant_internal::VariantCoreAccess::Replace<
  561. variant_internal::UnambiguousIndexOf<variant, T>::value>(
  562. this, il, absl::forward<Args>(args)...);
  563. }
  564. // Destroys the current value of the variant (provided that
  565. // `absl::valueless_by_exception()` is false, and constructs a new value at
  566. // the given index.
  567. //
  568. // Example:
  569. //
  570. // absl::variant<std::vector<int>, int, int> v;
  571. // v.emplace<1>(99);
  572. // v.emplace<2>(98);
  573. // v.emplace<int>(99); // Won't compile. 'int' isn't a unique type.
  574. template <std::size_t I, class... Args,
  575. typename std::enable_if<
  576. std::is_constructible<absl::variant_alternative_t<I, variant>,
  577. Args...>::value>::type* = nullptr>
  578. absl::variant_alternative_t<I, variant>& emplace(Args&&... args) {
  579. return variant_internal::VariantCoreAccess::Replace<I>(
  580. this, absl::forward<Args>(args)...);
  581. }
  582. // Destroys the current value of the variant (provided that
  583. // `absl::valueless_by_exception()` is false, and constructs a new value at
  584. // the given index using an initializer list and the provided arguments.
  585. //
  586. // Example:
  587. //
  588. // absl::variant<std::vector<int>, int, int> v;
  589. // v.emplace<0>({0, 1, 2});
  590. template <std::size_t I, class U, class... Args,
  591. typename std::enable_if<std::is_constructible<
  592. absl::variant_alternative_t<I, variant>,
  593. std::initializer_list<U>&, Args...>::value>::type* = nullptr>
  594. absl::variant_alternative_t<I, variant>& emplace(std::initializer_list<U> il,
  595. Args&&... args) {
  596. return variant_internal::VariantCoreAccess::Replace<I>(
  597. this, il, absl::forward<Args>(args)...);
  598. }
  599. // variant::valueless_by_exception()
  600. //
  601. // Returns false if and only if the variant currently holds a valid value.
  602. constexpr bool valueless_by_exception() const noexcept {
  603. return this->index_ == absl::variant_npos;
  604. }
  605. // variant::index()
  606. //
  607. // Returns the index value of the variant's currently selected alternative
  608. // type.
  609. constexpr std::size_t index() const noexcept { return this->index_; }
  610. // variant::swap()
  611. //
  612. // Swaps the values of two variant objects.
  613. //
  614. // TODO(calabrese)
  615. // `variant::swap()` and `swap()` rely on `std::is_(nothrow)_swappable()`
  616. // which is introduced in C++17. So we assume `is_swappable()` is always
  617. // true and `is_nothrow_swappable()` is same as `std::is_trivial()`.
  618. void swap(variant& rhs) noexcept(
  619. absl::conjunction<std::is_trivial<T0>, std::is_trivial<Tn>...>::value) {
  620. return variant_internal::VisitIndices<sizeof...(Tn) + 1>::Run(
  621. variant_internal::Swap<T0, Tn...>{this, &rhs}, rhs.index());
  622. }
  623. };
  624. // We need a valid declaration of variant<> for SFINAE and overload resolution
  625. // to work properly above, but we don't need a full declaration since this type
  626. // will never be constructed. This declaration, though incomplete, suffices.
  627. template <>
  628. class variant<>;
  629. //------------------------------------------------------------------------------
  630. // Relational Operators
  631. //------------------------------------------------------------------------------
  632. //
  633. // If neither operand is in the `variant::valueless_by_exception` state:
  634. //
  635. // * If the index of both variants is the same, the relational operator
  636. // returns the result of the corresponding relational operator for the
  637. // corresponding alternative type.
  638. // * If the index of both variants is not the same, the relational operator
  639. // returns the result of that operation applied to the value of the left
  640. // operand's index and the value of the right operand's index.
  641. // * If at least one operand is in the valueless_by_exception state:
  642. // - A variant in the valueless_by_exception state is only considered equal
  643. // to another variant in the valueless_by_exception state.
  644. // - If exactly one operand is in the valueless_by_exception state, the
  645. // variant in the valueless_by_exception state is less than the variant
  646. // that is not in the valueless_by_exception state.
  647. //
  648. // Note: The value 1 is added to each index in the relational comparisons such
  649. // that the index corresponding to the valueless_by_exception state wraps around
  650. // to 0 (the lowest value for the index type), and the remaining indices stay in
  651. // the same relative order.
  652. // Equal-to operator
  653. template <typename... Types>
  654. constexpr variant_internal::RequireAllHaveEqualT<Types...> operator==(
  655. const variant<Types...>& a, const variant<Types...>& b) {
  656. return (a.index() == b.index()) &&
  657. variant_internal::VisitIndices<sizeof...(Types)>::Run(
  658. variant_internal::EqualsOp<Types...>{&a, &b}, a.index());
  659. }
  660. // Not equal operator
  661. template <typename... Types>
  662. constexpr variant_internal::RequireAllHaveNotEqualT<Types...> operator!=(
  663. const variant<Types...>& a, const variant<Types...>& b) {
  664. return (a.index() != b.index()) ||
  665. variant_internal::VisitIndices<sizeof...(Types)>::Run(
  666. variant_internal::NotEqualsOp<Types...>{&a, &b}, a.index());
  667. }
  668. // Less-than operator
  669. template <typename... Types>
  670. constexpr variant_internal::RequireAllHaveLessThanT<Types...> operator<(
  671. const variant<Types...>& a, const variant<Types...>& b) {
  672. return (a.index() != b.index())
  673. ? (a.index() + 1) < (b.index() + 1)
  674. : variant_internal::VisitIndices<sizeof...(Types)>::Run(
  675. variant_internal::LessThanOp<Types...>{&a, &b}, a.index());
  676. }
  677. // Greater-than operator
  678. template <typename... Types>
  679. constexpr variant_internal::RequireAllHaveGreaterThanT<Types...> operator>(
  680. const variant<Types...>& a, const variant<Types...>& b) {
  681. return (a.index() != b.index())
  682. ? (a.index() + 1) > (b.index() + 1)
  683. : variant_internal::VisitIndices<sizeof...(Types)>::Run(
  684. variant_internal::GreaterThanOp<Types...>{&a, &b},
  685. a.index());
  686. }
  687. // Less-than or equal-to operator
  688. template <typename... Types>
  689. constexpr variant_internal::RequireAllHaveLessThanOrEqualT<Types...> operator<=(
  690. const variant<Types...>& a, const variant<Types...>& b) {
  691. return (a.index() != b.index())
  692. ? (a.index() + 1) < (b.index() + 1)
  693. : variant_internal::VisitIndices<sizeof...(Types)>::Run(
  694. variant_internal::LessThanOrEqualsOp<Types...>{&a, &b},
  695. a.index());
  696. }
  697. // Greater-than or equal-to operator
  698. template <typename... Types>
  699. constexpr variant_internal::RequireAllHaveGreaterThanOrEqualT<Types...>
  700. operator>=(const variant<Types...>& a, const variant<Types...>& b) {
  701. return (a.index() != b.index())
  702. ? (a.index() + 1) > (b.index() + 1)
  703. : variant_internal::VisitIndices<sizeof...(Types)>::Run(
  704. variant_internal::GreaterThanOrEqualsOp<Types...>{&a, &b},
  705. a.index());
  706. }
  707. } // inline namespace lts_2018_06_20
  708. } // namespace absl
  709. namespace std {
  710. // hash()
  711. template <> // NOLINT
  712. struct hash<absl::monostate> {
  713. std::size_t operator()(absl::monostate) const { return 0; }
  714. };
  715. template <class... T> // NOLINT
  716. struct hash<absl::variant<T...>>
  717. : absl::variant_internal::VariantHashBase<absl::variant<T...>, void,
  718. absl::remove_const_t<T>...> {};
  719. } // namespace std
  720. #endif // ABSL_HAVE_STD_VARIANT
  721. namespace absl {
  722. inline namespace lts_2018_06_20 {
  723. namespace variant_internal {
  724. // Helper visitor for converting a variant<Ts...>` into another type (mostly
  725. // variant) that can be constructed from any type.
  726. template <typename To>
  727. struct ConversionVisitor {
  728. template <typename T>
  729. To operator()(T&& v) const {
  730. return To(std::forward<T>(v));
  731. }
  732. };
  733. } // namespace variant_internal
  734. // ConvertVariantTo()
  735. //
  736. // Helper functions to convert an `absl::variant` to a variant of another set of
  737. // types, provided that the alternative type of the new variant type can be
  738. // converted from any type in the source variant.
  739. //
  740. // Example:
  741. //
  742. // absl::variant<name1, name2, float> InternalReq(const Req&);
  743. //
  744. // // name1 and name2 are convertible to name
  745. // absl::variant<name, float> ExternalReq(const Req& req) {
  746. // return absl::ConvertVariantTo<absl::variant<name, float>>(
  747. // InternalReq(req));
  748. // }
  749. template <typename To, typename Variant>
  750. To ConvertVariantTo(Variant&& variant) {
  751. return absl::visit(variant_internal::ConversionVisitor<To>{},
  752. std::forward<Variant>(variant));
  753. }
  754. } // inline namespace lts_2018_06_20
  755. } // namespace absl
  756. #endif // ABSL_TYPES_VARIANT_H_