• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2017 The Abseil Authors.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //      https://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 // optional.h
17 // -----------------------------------------------------------------------------
18 //
19 // This header file defines the `absl::optional` type for holding a value which
20 // may or may not be present. This type is useful for providing value semantics
21 // for operations that may either wish to return or hold "something-or-nothing".
22 //
23 // Example:
24 //
25 //   // A common way to signal operation failure is to provide an output
26 //   // parameter and a bool return type:
27 //   bool AcquireResource(const Input&, Resource * out);
28 //
29 //   // Providing an absl::optional return type provides a cleaner API:
30 //   absl::optional<Resource> AcquireResource(const Input&);
31 //
32 // `absl::optional` is a C++11 compatible version of the C++17 `std::optional`
33 // abstraction and is designed to be a drop-in replacement for code compliant
34 // with C++17.
35 #ifndef ABSL_TYPES_OPTIONAL_H_
36 #define ABSL_TYPES_OPTIONAL_H_
37 
38 #include "absl/base/config.h"   // TODO(calabrese) IWYU removal?
39 #include "absl/utility/utility.h"
40 
41 #ifdef ABSL_USES_STD_OPTIONAL
42 
43 #include <optional>  // IWYU pragma: export
44 
45 namespace absl {
46 ABSL_NAMESPACE_BEGIN
47 using std::bad_optional_access;
48 using std::optional;
49 using std::make_optional;
50 using std::nullopt_t;
51 using std::nullopt;
52 ABSL_NAMESPACE_END
53 }  // namespace absl
54 
55 #else  // ABSL_USES_STD_OPTIONAL
56 
57 #include <cassert>
58 #include <functional>
59 #include <initializer_list>
60 #include <type_traits>
61 #include <utility>
62 
63 #include "absl/base/attributes.h"
64 #include "absl/base/nullability.h"
65 #include "absl/base/internal/inline_variable.h"
66 #include "absl/meta/type_traits.h"
67 #include "absl/types/bad_optional_access.h"
68 #include "absl/types/internal/optional.h"
69 
70 namespace absl {
71 ABSL_NAMESPACE_BEGIN
72 
73 // nullopt_t
74 //
75 // Class type for `absl::nullopt` used to indicate an `absl::optional<T>` type
76 // that does not contain a value.
77 struct nullopt_t {
78   // It must not be default-constructible to avoid ambiguity for opt = {}.
nullopt_tnullopt_t79   explicit constexpr nullopt_t(optional_internal::init_t) noexcept {}
80 };
81 
82 // nullopt
83 //
84 // A tag constant of type `absl::nullopt_t` used to indicate an empty
85 // `absl::optional` in certain functions, such as construction or assignment.
86 ABSL_INTERNAL_INLINE_CONSTEXPR(nullopt_t, nullopt,
87                                nullopt_t(optional_internal::init_t()));
88 
89 // -----------------------------------------------------------------------------
90 // absl::optional
91 // -----------------------------------------------------------------------------
92 //
93 // A value of type `absl::optional<T>` holds either a value of `T` or an
94 // "empty" value.  When it holds a value of `T`, it stores it as a direct
95 // sub-object, so `sizeof(optional<T>)` is approximately
96 // `sizeof(T) + sizeof(bool)`.
97 //
98 // This implementation is based on the specification in the latest draft of the
99 // C++17 `std::optional` specification as of May 2017, section 20.6.
100 //
101 // Differences between `absl::optional<T>` and `std::optional<T>` include:
102 //
103 //    * `constexpr` is not used for non-const member functions.
104 //      (dependency on some differences between C++11 and C++14.)
105 //    * `absl::nullopt` and `absl::in_place` are not declared `constexpr`. We
106 //      need the inline variable support in C++17 for external linkage.
107 //    * Throws `absl::bad_optional_access` instead of
108 //      `std::bad_optional_access`.
109 //    * `make_optional()` cannot be declared `constexpr` due to the absence of
110 //      guaranteed copy elision.
111 //    * The move constructor's `noexcept` specification is stronger, i.e. if the
112 //      default allocator is non-throwing (via setting
113 //      `ABSL_ALLOCATOR_NOTHROW`), it evaluates to `noexcept(true)`, because
114 //      we assume
115 //       a) move constructors should only throw due to allocation failure and
116 //       b) if T's move constructor allocates, it uses the same allocation
117 //          function as the default allocator.
118 //
119 template <typename T>
120 class optional : private optional_internal::optional_data<T>,
121                  private optional_internal::optional_ctor_base<
122                      optional_internal::ctor_copy_traits<T>::traits>,
123                  private optional_internal::optional_assign_base<
124                      optional_internal::assign_copy_traits<T>::traits> {
125   using data_base = optional_internal::optional_data<T>;
126 
127  public:
128   typedef T value_type;
129 
130   // Constructors
131 
132   // Constructs an `optional` holding an empty value, NOT a default constructed
133   // `T`.
134   constexpr optional() noexcept = default;
135 
136   // Constructs an `optional` initialized with `nullopt` to hold an empty value.
optional(nullopt_t)137   constexpr optional(nullopt_t) noexcept {}  // NOLINT(runtime/explicit)
138 
139   // Copy constructor, standard semantics
140   optional(const optional&) = default;
141 
142   // Move constructor, standard semantics
143   optional(optional&&) = default;
144 
145   // Constructs a non-empty `optional` direct-initialized value of type `T` from
146   // the arguments `std::forward<Args>(args)...`  within the `optional`.
147   // (The `in_place_t` is a tag used to indicate that the contained object
148   // should be constructed in-place.)
149   template <typename InPlaceT, typename... Args,
150             absl::enable_if_t<absl::conjunction<
151                 std::is_same<InPlaceT, in_place_t>,
152                 std::is_constructible<T, Args&&...> >::value>* = nullptr>
optional(InPlaceT,Args &&...args)153   constexpr explicit optional(InPlaceT, Args&&... args)
154       : data_base(in_place_t(), std::forward<Args>(args)...) {}
155 
156   // Constructs a non-empty `optional` direct-initialized value of type `T` from
157   // the arguments of an initializer_list and `std::forward<Args>(args)...`.
158   // (The `in_place_t` is a tag used to indicate that the contained object
159   // should be constructed in-place.)
160   template <typename U, typename... Args,
161             typename = typename std::enable_if<std::is_constructible<
162                 T, std::initializer_list<U>&, Args&&...>::value>::type>
optional(in_place_t,std::initializer_list<U> il,Args &&...args)163   constexpr explicit optional(in_place_t, std::initializer_list<U> il,
164                               Args&&... args)
165       : data_base(in_place_t(), il, std::forward<Args>(args)...) {}
166 
167   // Value constructor (implicit)
168   template <
169       typename U = T,
170       typename std::enable_if<
171           absl::conjunction<absl::negation<std::is_same<
172                                 in_place_t, typename std::decay<U>::type> >,
173                             absl::negation<std::is_same<
174                                 optional<T>, typename std::decay<U>::type> >,
175                             std::is_convertible<U&&, T>,
176                             std::is_constructible<T, U&&> >::value,
177           bool>::type = false>
optional(U && v)178   constexpr optional(U&& v) : data_base(in_place_t(), std::forward<U>(v)) {}
179 
180   // Value constructor (explicit)
181   template <
182       typename U = T,
183       typename std::enable_if<
184           absl::conjunction<absl::negation<std::is_same<
185                                 in_place_t, typename std::decay<U>::type> >,
186                             absl::negation<std::is_same<
187                                 optional<T>, typename std::decay<U>::type> >,
188                             absl::negation<std::is_convertible<U&&, T> >,
189                             std::is_constructible<T, U&&> >::value,
190           bool>::type = false>
optional(U && v)191   explicit constexpr optional(U&& v)
192       : data_base(in_place_t(), std::forward<U>(v)) {}
193 
194   // Converting copy constructor (implicit)
195   template <typename U,
196             typename std::enable_if<
197                 absl::conjunction<
198                     absl::negation<std::is_same<T, U> >,
199                     std::is_constructible<T, const U&>,
200                     absl::negation<
201                         optional_internal::
202                             is_constructible_convertible_from_optional<T, U> >,
203                     std::is_convertible<const U&, T> >::value,
204                 bool>::type = false>
optional(const optional<U> & rhs)205   optional(const optional<U>& rhs) {
206     if (rhs) {
207       this->construct(*rhs);
208     }
209   }
210 
211   // Converting copy constructor (explicit)
212   template <typename U,
213             typename std::enable_if<
214                 absl::conjunction<
215                     absl::negation<std::is_same<T, U>>,
216                     std::is_constructible<T, const U&>,
217                     absl::negation<
218                         optional_internal::
219                             is_constructible_convertible_from_optional<T, U>>,
220                     absl::negation<std::is_convertible<const U&, T>>>::value,
221                 bool>::type = false>
optional(const optional<U> & rhs)222   explicit optional(const optional<U>& rhs) {
223     if (rhs) {
224       this->construct(*rhs);
225     }
226   }
227 
228   // Converting move constructor (implicit)
229   template <typename U,
230             typename std::enable_if<
231                 absl::conjunction<
232                     absl::negation<std::is_same<T, U> >,
233                     std::is_constructible<T, U&&>,
234                     absl::negation<
235                         optional_internal::
236                             is_constructible_convertible_from_optional<T, U> >,
237                     std::is_convertible<U&&, T> >::value,
238                 bool>::type = false>
optional(optional<U> && rhs)239   optional(optional<U>&& rhs) {
240     if (rhs) {
241       this->construct(std::move(*rhs));
242     }
243   }
244 
245   // Converting move constructor (explicit)
246   template <
247       typename U,
248       typename std::enable_if<
249           absl::conjunction<
250               absl::negation<std::is_same<T, U>>, std::is_constructible<T, U&&>,
251               absl::negation<
252                   optional_internal::is_constructible_convertible_from_optional<
253                       T, U>>,
254               absl::negation<std::is_convertible<U&&, T>>>::value,
255           bool>::type = false>
optional(optional<U> && rhs)256   explicit optional(optional<U>&& rhs) {
257     if (rhs) {
258       this->construct(std::move(*rhs));
259     }
260   }
261 
262   // Destructor. Trivial if `T` is trivially destructible.
263   ~optional() = default;
264 
265   // Assignment Operators
266 
267   // Assignment from `nullopt`
268   //
269   // Example:
270   //
271   //   struct S { int value; };
272   //   optional<S> opt = absl::nullopt;  // Could also use opt = { };
273   optional& operator=(nullopt_t) noexcept {
274     this->destruct();
275     return *this;
276   }
277 
278   // Copy assignment operator, standard semantics
279   optional& operator=(const optional& src) = default;
280 
281   // Move assignment operator, standard semantics
282   optional& operator=(optional&& src) = default;
283 
284   // Value assignment operators
285   template <typename U = T,
286             int&...,  // Workaround an internal compiler error in GCC 5 to 10.
287             typename = typename std::enable_if<absl::conjunction<
288                 absl::negation<
289                     std::is_same<optional<T>, typename std::decay<U>::type> >,
290                 absl::negation<absl::conjunction<
291                     std::is_scalar<T>,
292                     std::is_same<T, typename std::decay<U>::type> > >,
293                 std::is_constructible<T, U>,
294                 std::is_assignable<T&, U> >::value>::type>
295   optional& operator=(U&& v) {
296     this->assign(std::forward<U>(v));
297     return *this;
298   }
299 
300   template <
301       typename U,
302       int&...,  // Workaround an internal compiler error in GCC 5 to 10.
303       typename = typename std::enable_if<absl::conjunction<
304           absl::negation<std::is_same<T, U> >,
305           std::is_constructible<T, const U&>, std::is_assignable<T&, const U&>,
306           absl::negation<
307               optional_internal::
308                   is_constructible_convertible_assignable_from_optional<
309                       T, U> > >::value>::type>
310   optional& operator=(const optional<U>& rhs) {
311     if (rhs) {
312       this->assign(*rhs);
313     } else {
314       this->destruct();
315     }
316     return *this;
317   }
318 
319   template <typename U,
320             int&...,  // Workaround an internal compiler error in GCC 5 to 10.
321             typename = typename std::enable_if<absl::conjunction<
322                 absl::negation<std::is_same<T, U> >,
323                 std::is_constructible<T, U>, std::is_assignable<T&, U>,
324                 absl::negation<
325                     optional_internal::
326                         is_constructible_convertible_assignable_from_optional<
327                             T, U> > >::value>::type>
328   optional& operator=(optional<U>&& rhs) {
329     if (rhs) {
330       this->assign(std::move(*rhs));
331     } else {
332       this->destruct();
333     }
334     return *this;
335   }
336 
337   // Modifiers
338 
339   // optional::reset()
340   //
341   // Destroys the inner `T` value of an `absl::optional` if one is present.
reset()342   ABSL_ATTRIBUTE_REINITIALIZES void reset() noexcept { this->destruct(); }
343 
344   // optional::emplace()
345   //
346   // (Re)constructs the underlying `T` in-place with the given forwarded
347   // arguments.
348   //
349   // Example:
350   //
351   //   optional<Foo> opt;
352   //   opt.emplace(arg1,arg2,arg3);  // Constructs Foo(arg1,arg2,arg3)
353   //
354   // If the optional is non-empty, and the `args` refer to subobjects of the
355   // current object, then behaviour is undefined, because the current object
356   // will be destructed before the new object is constructed with `args`.
357   template <typename... Args,
358             typename = typename std::enable_if<
359                 std::is_constructible<T, Args&&...>::value>::type>
emplace(Args &&...args)360   T& emplace(Args&&... args) ABSL_ATTRIBUTE_LIFETIME_BOUND {
361     this->destruct();
362     this->construct(std::forward<Args>(args)...);
363     return reference();
364   }
365 
366   // Emplace reconstruction overload for an initializer list and the given
367   // forwarded arguments.
368   //
369   // Example:
370   //
371   //   struct Foo {
372   //     Foo(std::initializer_list<int>);
373   //   };
374   //
375   //   optional<Foo> opt;
376   //   opt.emplace({1,2,3});  // Constructs Foo({1,2,3})
377   template <typename U, typename... Args,
378             typename = typename std::enable_if<std::is_constructible<
379                 T, std::initializer_list<U>&, Args&&...>::value>::type>
emplace(std::initializer_list<U> il,Args &&...args)380   T& emplace(std::initializer_list<U> il,
381              Args&&... args) ABSL_ATTRIBUTE_LIFETIME_BOUND {
382     this->destruct();
383     this->construct(il, std::forward<Args>(args)...);
384     return reference();
385   }
386 
387   // Swaps
388 
389   // Swap, standard semantics
swap(optional & rhs)390   void swap(optional& rhs) noexcept(
391       std::is_nothrow_move_constructible<T>::value&&
392           type_traits_internal::IsNothrowSwappable<T>::value) {
393     if (*this) {
394       if (rhs) {
395         type_traits_internal::Swap(**this, *rhs);
396       } else {
397         rhs.construct(std::move(**this));
398         this->destruct();
399       }
400     } else {
401       if (rhs) {
402         this->construct(std::move(*rhs));
403         rhs.destruct();
404       } else {
405         // No effect (swap(disengaged, disengaged)).
406       }
407     }
408   }
409 
410   // Observers
411 
412   // optional::operator->()
413   //
414   // Accesses the underlying `T` value's member `m` of an `optional`. If the
415   // `optional` is empty, behavior is undefined.
416   //
417   // If you need myOpt->foo in constexpr, use (*myOpt).foo instead.
418   absl::Nonnull<const T*> operator->() const ABSL_ATTRIBUTE_LIFETIME_BOUND {
419     ABSL_HARDENING_ASSERT(this->engaged_);
420     return std::addressof(this->data_);
421   }
422   absl::Nonnull<T*> operator->() ABSL_ATTRIBUTE_LIFETIME_BOUND {
423     ABSL_HARDENING_ASSERT(this->engaged_);
424     return std::addressof(this->data_);
425   }
426 
427   // optional::operator*()
428   //
429   // Accesses the underlying `T` value of an `optional`. If the `optional` is
430   // empty, behavior is undefined.
431   constexpr const T& operator*() const& ABSL_ATTRIBUTE_LIFETIME_BOUND {
432     return ABSL_HARDENING_ASSERT(this->engaged_), reference();
433   }
434   T& operator*() & ABSL_ATTRIBUTE_LIFETIME_BOUND {
435     ABSL_HARDENING_ASSERT(this->engaged_);
436     return reference();
437   }
438   constexpr const T&& operator*() const&& ABSL_ATTRIBUTE_LIFETIME_BOUND {
439     return ABSL_HARDENING_ASSERT(this->engaged_), std::move(reference());
440   }
441   T&& operator*() && ABSL_ATTRIBUTE_LIFETIME_BOUND {
442     ABSL_HARDENING_ASSERT(this->engaged_);
443     return std::move(reference());
444   }
445 
446   // optional::operator bool()
447   //
448   // Returns false if and only if the `optional` is empty.
449   //
450   //   if (opt) {
451   //     // do something with *opt or opt->;
452   //   } else {
453   //     // opt is empty.
454   //   }
455   //
456   constexpr explicit operator bool() const noexcept { return this->engaged_; }
457 
458   // optional::has_value()
459   //
460   // Determines whether the `optional` contains a value. Returns `false` if and
461   // only if `*this` is empty.
has_value()462   constexpr bool has_value() const noexcept { return this->engaged_; }
463 
464 // Suppress bogus warning on MSVC: MSVC complains call to reference() after
465 // throw_bad_optional_access() is unreachable.
466 #ifdef _MSC_VER
467 #pragma warning(push)
468 #pragma warning(disable : 4702)
469 #endif  // _MSC_VER
470   // optional::value()
471   //
472   // Returns a reference to an `optional`s underlying value. The constness
473   // and lvalue/rvalue-ness of the `optional` is preserved to the view of
474   // the `T` sub-object. Throws `absl::bad_optional_access` when the `optional`
475   // is empty.
value()476   constexpr const T& value() const& ABSL_ATTRIBUTE_LIFETIME_BOUND {
477     return static_cast<bool>(*this)
478                ? reference()
479                : (optional_internal::throw_bad_optional_access(), reference());
480   }
value()481   T& value() & ABSL_ATTRIBUTE_LIFETIME_BOUND {
482     return static_cast<bool>(*this)
483                ? reference()
484                : (optional_internal::throw_bad_optional_access(), reference());
485   }
value()486   T&& value() && ABSL_ATTRIBUTE_LIFETIME_BOUND {  // NOLINT(build/c++11)
487     return std::move(
488         static_cast<bool>(*this)
489             ? reference()
490             : (optional_internal::throw_bad_optional_access(), reference()));
491   }
value()492   constexpr const T&& value()
493       const&& ABSL_ATTRIBUTE_LIFETIME_BOUND {  // NOLINT(build/c++11)
494     return std::move(
495         static_cast<bool>(*this)
496             ? reference()
497             : (optional_internal::throw_bad_optional_access(), reference()));
498   }
499 #ifdef _MSC_VER
500 #pragma warning(pop)
501 #endif  // _MSC_VER
502 
503   // optional::value_or()
504   //
505   // Returns either the value of `T` or a passed default `v` if the `optional`
506   // is empty.
507   template <typename U>
value_or(U && v)508   constexpr T value_or(U&& v) const& {
509     static_assert(std::is_copy_constructible<value_type>::value,
510                   "optional<T>::value_or: T must be copy constructible");
511     static_assert(std::is_convertible<U&&, value_type>::value,
512                   "optional<T>::value_or: U must be convertible to T");
513     return static_cast<bool>(*this) ? **this
514                                     : static_cast<T>(std::forward<U>(v));
515   }
516   template <typename U>
value_or(U && v)517   T value_or(U&& v) && {  // NOLINT(build/c++11)
518     static_assert(std::is_move_constructible<value_type>::value,
519                   "optional<T>::value_or: T must be move constructible");
520     static_assert(std::is_convertible<U&&, value_type>::value,
521                   "optional<T>::value_or: U must be convertible to T");
522     return static_cast<bool>(*this) ? std::move(**this)
523                                     : static_cast<T>(std::forward<U>(v));
524   }
525 
526  private:
527   // Private accessors for internal storage viewed as reference to T.
reference()528   constexpr const T& reference() const { return this->data_; }
reference()529   T& reference() { return this->data_; }
530 
531   // T constraint checks.  You can't have an optional of nullopt_t, in_place_t
532   // or a reference.
533   static_assert(
534       !std::is_same<nullopt_t, typename std::remove_cv<T>::type>::value,
535       "optional<nullopt_t> is not allowed.");
536   static_assert(
537       !std::is_same<in_place_t, typename std::remove_cv<T>::type>::value,
538       "optional<in_place_t> is not allowed.");
539   static_assert(!std::is_reference<T>::value,
540                 "optional<reference> is not allowed.");
541 };
542 
543 // Non-member functions
544 
545 // swap()
546 //
547 // Performs a swap between two `absl::optional` objects, using standard
548 // semantics.
549 template <typename T, typename std::enable_if<
550                           std::is_move_constructible<T>::value &&
551                               type_traits_internal::IsSwappable<T>::value,
552                           bool>::type = false>
swap(optional<T> & a,optional<T> & b)553 void swap(optional<T>& a, optional<T>& b) noexcept(noexcept(a.swap(b))) {
554   a.swap(b);
555 }
556 
557 // make_optional()
558 //
559 // Creates a non-empty `optional<T>` where the type of `T` is deduced. An
560 // `absl::optional` can also be explicitly instantiated with
561 // `make_optional<T>(v)`.
562 //
563 // Note: `make_optional()` constructions may be declared `constexpr` for
564 // trivially copyable types `T`. Non-trivial types require copy elision
565 // support in C++17 for `make_optional` to support `constexpr` on such
566 // non-trivial types.
567 //
568 // Example:
569 //
570 //   constexpr absl::optional<int> opt = absl::make_optional(1);
571 //   static_assert(opt.value() == 1, "");
572 template <typename T>
make_optional(T && v)573 constexpr optional<typename std::decay<T>::type> make_optional(T&& v) {
574   return optional<typename std::decay<T>::type>(std::forward<T>(v));
575 }
576 
577 template <typename T, typename... Args>
make_optional(Args &&...args)578 constexpr optional<T> make_optional(Args&&... args) {
579   return optional<T>(in_place_t(), std::forward<Args>(args)...);
580 }
581 
582 template <typename T, typename U, typename... Args>
make_optional(std::initializer_list<U> il,Args &&...args)583 constexpr optional<T> make_optional(std::initializer_list<U> il,
584                                     Args&&... args) {
585   return optional<T>(in_place_t(), il, std::forward<Args>(args)...);
586 }
587 
588 // Relational operators [optional.relops]
589 
590 // Empty optionals are considered equal to each other and less than non-empty
591 // optionals. Supports relations between optional<T> and optional<U>, between
592 // optional<T> and U, and between optional<T> and nullopt.
593 //
594 // Note: We're careful to support T having non-bool relationals.
595 
596 // Requires: The expression, e.g. "*x == *y" shall be well-formed and its result
597 // shall be convertible to bool.
598 // The C++17 (N4606) "Returns:" statements are translated into
599 // code in an obvious way here, and the original text retained as function docs.
600 // Returns: If bool(x) != bool(y), false; otherwise if bool(x) == false, true;
601 // otherwise *x == *y.
602 template <typename T, typename U>
603 constexpr auto operator==(const optional<T>& x, const optional<U>& y)
604     -> decltype(optional_internal::convertible_to_bool(*x == *y)) {
605   return static_cast<bool>(x) != static_cast<bool>(y)
606              ? false
607              : static_cast<bool>(x) == false ? true
608                                              : static_cast<bool>(*x == *y);
609 }
610 
611 // Returns: If bool(x) != bool(y), true; otherwise, if bool(x) == false, false;
612 // otherwise *x != *y.
613 template <typename T, typename U>
614 constexpr auto operator!=(const optional<T>& x, const optional<U>& y)
615     -> decltype(optional_internal::convertible_to_bool(*x != *y)) {
616   return static_cast<bool>(x) != static_cast<bool>(y)
617              ? true
618              : static_cast<bool>(x) == false ? false
619                                              : static_cast<bool>(*x != *y);
620 }
621 // Returns: If !y, false; otherwise, if !x, true; otherwise *x < *y.
622 template <typename T, typename U>
623 constexpr auto operator<(const optional<T>& x, const optional<U>& y)
624     -> decltype(optional_internal::convertible_to_bool(*x < *y)) {
625   return !y ? false : !x ? true : static_cast<bool>(*x < *y);
626 }
627 // Returns: If !x, false; otherwise, if !y, true; otherwise *x > *y.
628 template <typename T, typename U>
629 constexpr auto operator>(const optional<T>& x, const optional<U>& y)
630     -> decltype(optional_internal::convertible_to_bool(*x > *y)) {
631   return !x ? false : !y ? true : static_cast<bool>(*x > *y);
632 }
633 // Returns: If !x, true; otherwise, if !y, false; otherwise *x <= *y.
634 template <typename T, typename U>
635 constexpr auto operator<=(const optional<T>& x, const optional<U>& y)
636     -> decltype(optional_internal::convertible_to_bool(*x <= *y)) {
637   return !x ? true : !y ? false : static_cast<bool>(*x <= *y);
638 }
639 // Returns: If !y, true; otherwise, if !x, false; otherwise *x >= *y.
640 template <typename T, typename U>
641 constexpr auto operator>=(const optional<T>& x, const optional<U>& y)
642     -> decltype(optional_internal::convertible_to_bool(*x >= *y)) {
643   return !y ? true : !x ? false : static_cast<bool>(*x >= *y);
644 }
645 
646 // Comparison with nullopt [optional.nullops]
647 // The C++17 (N4606) "Returns:" statements are used directly here.
648 template <typename T>
649 constexpr bool operator==(const optional<T>& x, nullopt_t) noexcept {
650   return !x;
651 }
652 template <typename T>
653 constexpr bool operator==(nullopt_t, const optional<T>& x) noexcept {
654   return !x;
655 }
656 template <typename T>
657 constexpr bool operator!=(const optional<T>& x, nullopt_t) noexcept {
658   return static_cast<bool>(x);
659 }
660 template <typename T>
661 constexpr bool operator!=(nullopt_t, const optional<T>& x) noexcept {
662   return static_cast<bool>(x);
663 }
664 template <typename T>
665 constexpr bool operator<(const optional<T>&, nullopt_t) noexcept {
666   return false;
667 }
668 template <typename T>
669 constexpr bool operator<(nullopt_t, const optional<T>& x) noexcept {
670   return static_cast<bool>(x);
671 }
672 template <typename T>
673 constexpr bool operator<=(const optional<T>& x, nullopt_t) noexcept {
674   return !x;
675 }
676 template <typename T>
677 constexpr bool operator<=(nullopt_t, const optional<T>&) noexcept {
678   return true;
679 }
680 template <typename T>
681 constexpr bool operator>(const optional<T>& x, nullopt_t) noexcept {
682   return static_cast<bool>(x);
683 }
684 template <typename T>
685 constexpr bool operator>(nullopt_t, const optional<T>&) noexcept {
686   return false;
687 }
688 template <typename T>
689 constexpr bool operator>=(const optional<T>&, nullopt_t) noexcept {
690   return true;
691 }
692 template <typename T>
693 constexpr bool operator>=(nullopt_t, const optional<T>& x) noexcept {
694   return !x;
695 }
696 
697 // Comparison with T [optional.comp_with_t]
698 
699 // Requires: The expression, e.g. "*x == v" shall be well-formed and its result
700 // shall be convertible to bool.
701 // The C++17 (N4606) "Equivalent to:" statements are used directly here.
702 template <typename T, typename U>
703 constexpr auto operator==(const optional<T>& x, const U& v)
704     -> decltype(optional_internal::convertible_to_bool(*x == v)) {
705   return static_cast<bool>(x) ? static_cast<bool>(*x == v) : false;
706 }
707 template <typename T, typename U>
708 constexpr auto operator==(const U& v, const optional<T>& x)
709     -> decltype(optional_internal::convertible_to_bool(v == *x)) {
710   return static_cast<bool>(x) ? static_cast<bool>(v == *x) : false;
711 }
712 template <typename T, typename U>
713 constexpr auto operator!=(const optional<T>& x, const U& v)
714     -> decltype(optional_internal::convertible_to_bool(*x != v)) {
715   return static_cast<bool>(x) ? static_cast<bool>(*x != v) : true;
716 }
717 template <typename T, typename U>
718 constexpr auto operator!=(const U& v, const optional<T>& x)
719     -> decltype(optional_internal::convertible_to_bool(v != *x)) {
720   return static_cast<bool>(x) ? static_cast<bool>(v != *x) : true;
721 }
722 template <typename T, typename U>
723 constexpr auto operator<(const optional<T>& x, const U& v)
724     -> decltype(optional_internal::convertible_to_bool(*x < v)) {
725   return static_cast<bool>(x) ? static_cast<bool>(*x < v) : true;
726 }
727 template <typename T, typename U>
728 constexpr auto operator<(const U& v, const optional<T>& x)
729     -> decltype(optional_internal::convertible_to_bool(v < *x)) {
730   return static_cast<bool>(x) ? static_cast<bool>(v < *x) : false;
731 }
732 template <typename T, typename U>
733 constexpr auto operator<=(const optional<T>& x, const U& v)
734     -> decltype(optional_internal::convertible_to_bool(*x <= v)) {
735   return static_cast<bool>(x) ? static_cast<bool>(*x <= v) : true;
736 }
737 template <typename T, typename U>
738 constexpr auto operator<=(const U& v, const optional<T>& x)
739     -> decltype(optional_internal::convertible_to_bool(v <= *x)) {
740   return static_cast<bool>(x) ? static_cast<bool>(v <= *x) : false;
741 }
742 template <typename T, typename U>
743 constexpr auto operator>(const optional<T>& x, const U& v)
744     -> decltype(optional_internal::convertible_to_bool(*x > v)) {
745   return static_cast<bool>(x) ? static_cast<bool>(*x > v) : false;
746 }
747 template <typename T, typename U>
748 constexpr auto operator>(const U& v, const optional<T>& x)
749     -> decltype(optional_internal::convertible_to_bool(v > *x)) {
750   return static_cast<bool>(x) ? static_cast<bool>(v > *x) : true;
751 }
752 template <typename T, typename U>
753 constexpr auto operator>=(const optional<T>& x, const U& v)
754     -> decltype(optional_internal::convertible_to_bool(*x >= v)) {
755   return static_cast<bool>(x) ? static_cast<bool>(*x >= v) : false;
756 }
757 template <typename T, typename U>
758 constexpr auto operator>=(const U& v, const optional<T>& x)
759     -> decltype(optional_internal::convertible_to_bool(v >= *x)) {
760   return static_cast<bool>(x) ? static_cast<bool>(v >= *x) : true;
761 }
762 
763 ABSL_NAMESPACE_END
764 }  // namespace absl
765 
766 namespace std {
767 
768 // std::hash specialization for absl::optional.
769 template <typename T>
770 struct hash<absl::optional<T> >
771     : absl::optional_internal::optional_hash_base<T> {};
772 
773 }  // namespace std
774 
775 #undef ABSL_MSVC_CONSTEXPR_BUG_IN_UNION_LIKE_CLASS
776 
777 #endif  // ABSL_USES_STD_OPTIONAL
778 
779 #endif  // ABSL_TYPES_OPTIONAL_H_
780