1 // Copyright 2017 The Abseil Authors.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 //
15 // -----------------------------------------------------------------------------
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"
39 #include "absl/utility/utility.h"
40
41 #ifdef ABSL_HAVE_STD_OPTIONAL
42
43 #include <optional>
44
45 namespace absl {
46 using std::bad_optional_access;
47 using std::optional;
48 using std::make_optional;
49 using std::nullopt_t;
50 using std::nullopt;
51 } // namespace absl
52
53 #else // ABSL_HAVE_STD_OPTIONAL
54
55 #include <cassert>
56 #include <functional>
57 #include <initializer_list>
58 #include <new>
59 #include <type_traits>
60 #include <utility>
61
62 #include "absl/memory/memory.h"
63 #include "absl/meta/type_traits.h"
64 #include "absl/types/bad_optional_access.h"
65
66 // ABSL_OPTIONAL_USE_INHERITING_CONSTRUCTORS
67 //
68 // Inheriting constructors is supported in GCC 4.8+, Clang 3.3+ and MSVC 2015.
69 // __cpp_inheriting_constructors is a predefined macro and a recommended way to
70 // check for this language feature, but GCC doesn't support it until 5.0 and
71 // Clang doesn't support it until 3.6.
72 // Also, MSVC 2015 has a bug: it doesn't inherit the constexpr template
73 // constructor. For example, the following code won't work on MSVC 2015 Update3:
74 // struct Base {
75 // int t;
76 // template <typename T>
77 // constexpr Base(T t_) : t(t_) {}
78 // };
79 // struct Foo : Base {
80 // using Base::Base;
81 // }
82 // constexpr Foo foo(0); // doesn't work on MSVC 2015
83 #if defined(__clang__)
84 #if __has_feature(cxx_inheriting_constructors)
85 #define ABSL_OPTIONAL_USE_INHERITING_CONSTRUCTORS 1
86 #endif
87 #elif (defined(__GNUC__) && \
88 (__GNUC__ > 4 || __GNUC__ == 4 && __GNUC_MINOR__ >= 8)) || \
89 (__cpp_inheriting_constructors >= 200802) || \
90 (defined(_MSC_VER) && _MSC_VER >= 1910)
91 #define ABSL_OPTIONAL_USE_INHERITING_CONSTRUCTORS 1
92 #endif
93
94 namespace absl {
95
96 // -----------------------------------------------------------------------------
97 // absl::optional
98 // -----------------------------------------------------------------------------
99 //
100 // A value of type `absl::optional<T>` holds either a value of `T` or an
101 // "empty" value. When it holds a value of `T`, it stores it as a direct
102 // sub-object, so `sizeof(optional<T>)` is approximately
103 // `sizeof(T) + sizeof(bool)`.
104 //
105 // This implementation is based on the specification in the latest draft of the
106 // C++17 `std::optional` specification as of May 2017, section 20.6.
107 //
108 // Differences between `absl::optional<T>` and `std::optional<T>` include:
109 //
110 // * `constexpr` is not used for non-const member functions.
111 // (dependency on some differences between C++11 and C++14.)
112 // * `absl::nullopt` and `absl::in_place` are not declared `constexpr`. We
113 // need the inline variable support in C++17 for external linkage.
114 // * Throws `absl::bad_optional_access` instead of
115 // `std::bad_optional_access`.
116 // * `optional::swap()` and `absl::swap()` relies on
117 // `std::is_(nothrow_)swappable()`, which has been introduced in C++17.
118 // As a workaround, we assume `is_swappable()` is always `true`
119 // and `is_nothrow_swappable()` is the same as `std::is_trivial()`.
120 // * `make_optional()` cannot be declared `constexpr` due to the absence of
121 // guaranteed copy elision.
122 // * The move constructor's `noexcept` specification is stronger, i.e. if the
123 // default allocator is non-throwing (via setting
124 // `ABSL_ALLOCATOR_NOTHROW`), it evaluates to `noexcept(true)`, because
125 // we assume
126 // a) move constructors should only throw due to allocation failure and
127 // b) if T's move constructor allocates, it uses the same allocation
128 // function as the default allocator.
129 template <typename T>
130 class optional;
131
132 // nullopt_t
133 //
134 // Class type for `absl::nullopt` used to indicate an `absl::optional<T>` type
135 // that does not contain a value.
136 struct nullopt_t {
137 struct init_t {};
138 static init_t init;
139
140 // It must not be default-constructible to avoid ambiguity for opt = {}.
141 // Note the non-const reference, which is to eliminate ambiguity for code
142 // like:
143 //
144 // struct S { int value; };
145 //
146 // void Test() {
147 // optional<S> opt;
148 // opt = {{}};
149 // }
nullopt_tnullopt_t150 explicit constexpr nullopt_t(init_t& /*unused*/) {}
151 };
152
153 // nullopt
154 //
155 // A tag constant of type `absl::nullopt_t` used to indicate an empty
156 // `absl::optional` in certain functions, such as construction or assignment.
157 extern const nullopt_t nullopt;
158
159 namespace optional_internal {
160
161 struct empty_struct {};
162 // This class stores the data in optional<T>.
163 // It is specialized based on whether T is trivially destructible.
164 // This is the specialization for non trivially destructible type.
165 template <typename T, bool = std::is_trivially_destructible<T>::value>
166 class optional_data_dtor_base {
167 struct dummy_type {
168 static_assert(sizeof(T) % sizeof(empty_struct) == 0, "");
169 // Use an array to avoid GCC 6 placement-new warning.
170 empty_struct data[sizeof(T) / sizeof(empty_struct)];
171 };
172
173 protected:
174 // Whether there is data or not.
175 bool engaged_;
176 // Data storage
177 union {
178 dummy_type dummy_;
179 T data_;
180 };
181
destruct()182 void destruct() noexcept {
183 if (engaged_) {
184 data_.~T();
185 engaged_ = false;
186 }
187 }
188
189 // dummy_ must be initialized for constexpr constructor.
optional_data_dtor_base()190 constexpr optional_data_dtor_base() noexcept : engaged_(false), dummy_{{}} {}
191
192 template <typename... Args>
optional_data_dtor_base(in_place_t,Args &&...args)193 constexpr explicit optional_data_dtor_base(in_place_t, Args&&... args)
194 : engaged_(true), data_(absl::forward<Args>(args)...) {}
195
~optional_data_dtor_base()196 ~optional_data_dtor_base() { destruct(); }
197 };
198
199 // Specialization for trivially destructible type.
200 template <typename T>
201 class optional_data_dtor_base<T, true> {
202 struct dummy_type {
203 static_assert(sizeof(T) % sizeof(empty_struct) == 0, "");
204 // Use array to avoid GCC 6 placement-new warning.
205 empty_struct data[sizeof(T) / sizeof(empty_struct)];
206 };
207
208 protected:
209 // Whether there is data or not.
210 bool engaged_;
211 // Data storage
212 union {
213 dummy_type dummy_;
214 T data_;
215 };
destruct()216 void destruct() noexcept { engaged_ = false; }
217
218 // dummy_ must be initialized for constexpr constructor.
optional_data_dtor_base()219 constexpr optional_data_dtor_base() noexcept : engaged_(false), dummy_{{}} {}
220
221 template <typename... Args>
optional_data_dtor_base(in_place_t,Args &&...args)222 constexpr explicit optional_data_dtor_base(in_place_t, Args&&... args)
223 : engaged_(true), data_(absl::forward<Args>(args)...) {}
224 };
225
226 template <typename T>
227 class optional_data_base : public optional_data_dtor_base<T> {
228 protected:
229 using base = optional_data_dtor_base<T>;
230 #if ABSL_OPTIONAL_USE_INHERITING_CONSTRUCTORS
231 using base::base;
232 #else
233 optional_data_base() = default;
234
235 template <typename... Args>
optional_data_base(in_place_t t,Args &&...args)236 constexpr explicit optional_data_base(in_place_t t, Args&&... args)
237 : base(t, absl::forward<Args>(args)...) {}
238 #endif
239
240 template <typename... Args>
construct(Args &&...args)241 void construct(Args&&... args) {
242 // Use dummy_'s address to work around casting cv-qualified T* to void*.
243 ::new (static_cast<void*>(&this->dummy_)) T(std::forward<Args>(args)...);
244 this->engaged_ = true;
245 }
246
247 template <typename U>
assign(U && u)248 void assign(U&& u) {
249 if (this->engaged_) {
250 this->data_ = std::forward<U>(u);
251 } else {
252 construct(std::forward<U>(u));
253 }
254 }
255 };
256
257 // TODO(absl-team): Add another class using
258 // std::is_trivially_move_constructible trait when available to match
259 // http://cplusplus.github.io/LWG/lwg-defects.html#2900, for types that
260 // have trivial move but nontrivial copy.
261 // Also, we should be checking is_trivially_copyable here, which is not
262 // supported now, so we use is_trivially_* traits instead.
263 template <typename T, bool = absl::is_trivially_copy_constructible<T>::value&&
264 absl::is_trivially_copy_assignable<
265 typename std::remove_cv<T>::type>::value&&
266 std::is_trivially_destructible<T>::value>
267 class optional_data;
268
269 // Trivially copyable types
270 template <typename T>
271 class optional_data<T, true> : public optional_data_base<T> {
272 protected:
273 #if ABSL_OPTIONAL_USE_INHERITING_CONSTRUCTORS
274 using optional_data_base<T>::optional_data_base;
275 #else
276 optional_data() = default;
277
278 template <typename... Args>
279 constexpr explicit optional_data(in_place_t t, Args&&... args)
280 : optional_data_base<T>(t, absl::forward<Args>(args)...) {}
281 #endif
282 };
283
284 template <typename T>
285 class optional_data<T, false> : public optional_data_base<T> {
286 protected:
287 #if ABSL_OPTIONAL_USE_INHERITING_CONSTRUCTORS
288 using optional_data_base<T>::optional_data_base;
289 #else
290 template <typename... Args>
291 constexpr explicit optional_data(in_place_t t, Args&&... args)
292 : optional_data_base<T>(t, absl::forward<Args>(args)...) {}
293 #endif
294
295 optional_data() = default;
296
optional_data(const optional_data & rhs)297 optional_data(const optional_data& rhs) {
298 if (rhs.engaged_) {
299 this->construct(rhs.data_);
300 }
301 }
302
303 optional_data(optional_data&& rhs) noexcept(
304 absl::default_allocator_is_nothrow::value ||
305 std::is_nothrow_move_constructible<T>::value) {
306 if (rhs.engaged_) {
307 this->construct(std::move(rhs.data_));
308 }
309 }
310
311 optional_data& operator=(const optional_data& rhs) {
312 if (rhs.engaged_) {
313 this->assign(rhs.data_);
314 } else {
315 this->destruct();
316 }
317 return *this;
318 }
319
noexcept(std::is_nothrow_move_assignable<T>::value && std::is_nothrow_move_constructible<T>::value)320 optional_data& operator=(optional_data&& rhs) noexcept(
321 std::is_nothrow_move_assignable<T>::value&&
322 std::is_nothrow_move_constructible<T>::value) {
323 if (rhs.engaged_) {
324 this->assign(std::move(rhs.data_));
325 } else {
326 this->destruct();
327 }
328 return *this;
329 }
330 };
331
332 // Ordered by level of restriction, from low to high.
333 // Copyable implies movable.
334 enum class copy_traits { copyable = 0, movable = 1, non_movable = 2 };
335
336 // Base class for enabling/disabling copy/move constructor.
337 template <copy_traits>
338 class optional_ctor_base;
339
340 template <>
341 class optional_ctor_base<copy_traits::copyable> {
342 public:
343 constexpr optional_ctor_base() = default;
344 optional_ctor_base(const optional_ctor_base&) = default;
345 optional_ctor_base(optional_ctor_base&&) = default;
346 optional_ctor_base& operator=(const optional_ctor_base&) = default;
347 optional_ctor_base& operator=(optional_ctor_base&&) = default;
348 };
349
350 template <>
351 class optional_ctor_base<copy_traits::movable> {
352 public:
353 constexpr optional_ctor_base() = default;
354 optional_ctor_base(const optional_ctor_base&) = delete;
355 optional_ctor_base(optional_ctor_base&&) = default;
356 optional_ctor_base& operator=(const optional_ctor_base&) = default;
357 optional_ctor_base& operator=(optional_ctor_base&&) = default;
358 };
359
360 template <>
361 class optional_ctor_base<copy_traits::non_movable> {
362 public:
363 constexpr optional_ctor_base() = default;
364 optional_ctor_base(const optional_ctor_base&) = delete;
365 optional_ctor_base(optional_ctor_base&&) = delete;
366 optional_ctor_base& operator=(const optional_ctor_base&) = default;
367 optional_ctor_base& operator=(optional_ctor_base&&) = default;
368 };
369
370 // Base class for enabling/disabling copy/move assignment.
371 template <copy_traits>
372 class optional_assign_base;
373
374 template <>
375 class optional_assign_base<copy_traits::copyable> {
376 public:
377 constexpr optional_assign_base() = default;
378 optional_assign_base(const optional_assign_base&) = default;
379 optional_assign_base(optional_assign_base&&) = default;
380 optional_assign_base& operator=(const optional_assign_base&) = default;
381 optional_assign_base& operator=(optional_assign_base&&) = default;
382 };
383
384 template <>
385 class optional_assign_base<copy_traits::movable> {
386 public:
387 constexpr optional_assign_base() = default;
388 optional_assign_base(const optional_assign_base&) = default;
389 optional_assign_base(optional_assign_base&&) = default;
390 optional_assign_base& operator=(const optional_assign_base&) = delete;
391 optional_assign_base& operator=(optional_assign_base&&) = default;
392 };
393
394 template <>
395 class optional_assign_base<copy_traits::non_movable> {
396 public:
397 constexpr optional_assign_base() = default;
398 optional_assign_base(const optional_assign_base&) = default;
399 optional_assign_base(optional_assign_base&&) = default;
400 optional_assign_base& operator=(const optional_assign_base&) = delete;
401 optional_assign_base& operator=(optional_assign_base&&) = delete;
402 };
403
404 template <typename T>
get_ctor_copy_traits()405 constexpr copy_traits get_ctor_copy_traits() {
406 return std::is_copy_constructible<T>::value
407 ? copy_traits::copyable
408 : std::is_move_constructible<T>::value ? copy_traits::movable
409 : copy_traits::non_movable;
410 }
411
412 template <typename T>
get_assign_copy_traits()413 constexpr copy_traits get_assign_copy_traits() {
414 return std::is_copy_assignable<T>::value &&
415 std::is_copy_constructible<T>::value
416 ? copy_traits::copyable
417 : std::is_move_assignable<T>::value &&
418 std::is_move_constructible<T>::value
419 ? copy_traits::movable
420 : copy_traits::non_movable;
421 }
422
423 // Whether T is constructible or convertible from optional<U>.
424 template <typename T, typename U>
425 struct is_constructible_convertible_from_optional
426 : std::integral_constant<
427 bool, std::is_constructible<T, optional<U>&>::value ||
428 std::is_constructible<T, optional<U>&&>::value ||
429 std::is_constructible<T, const optional<U>&>::value ||
430 std::is_constructible<T, const optional<U>&&>::value ||
431 std::is_convertible<optional<U>&, T>::value ||
432 std::is_convertible<optional<U>&&, T>::value ||
433 std::is_convertible<const optional<U>&, T>::value ||
434 std::is_convertible<const optional<U>&&, T>::value> {};
435
436 // Whether T is constructible or convertible or assignable from optional<U>.
437 template <typename T, typename U>
438 struct is_constructible_convertible_assignable_from_optional
439 : std::integral_constant<
440 bool, is_constructible_convertible_from_optional<T, U>::value ||
441 std::is_assignable<T&, optional<U>&>::value ||
442 std::is_assignable<T&, optional<U>&&>::value ||
443 std::is_assignable<T&, const optional<U>&>::value ||
444 std::is_assignable<T&, const optional<U>&&>::value> {};
445
446 // Helper function used by [optional.relops], [optional.comp_with_t],
447 // for checking whether an expression is convertible to bool.
448 bool convertible_to_bool(bool);
449
450 // Base class for std::hash<absl::optional<T>>:
451 // If std::hash<std::remove_const_t<T>> is enabled, it provides operator() to
452 // compute the hash; Otherwise, it is disabled.
453 // Reference N4659 23.14.15 [unord.hash].
454 template <typename T, typename = size_t>
455 struct optional_hash_base {
456 optional_hash_base() = delete;
457 optional_hash_base(const optional_hash_base&) = delete;
458 optional_hash_base(optional_hash_base&&) = delete;
459 optional_hash_base& operator=(const optional_hash_base&) = delete;
460 optional_hash_base& operator=(optional_hash_base&&) = delete;
461 };
462
463 template <typename T>
464 struct optional_hash_base<T, decltype(std::hash<absl::remove_const_t<T> >()(
465 std::declval<absl::remove_const_t<T> >()))> {
466 using argument_type = absl::optional<T>;
467 using result_type = size_t;
468 size_t operator()(const absl::optional<T>& opt) const {
469 if (opt) {
470 return std::hash<absl::remove_const_t<T> >()(*opt);
471 } else {
472 return static_cast<size_t>(0x297814aaad196e6dULL);
473 }
474 }
475 };
476
477 } // namespace optional_internal
478
479 // -----------------------------------------------------------------------------
480 // absl::optional class definition
481 // -----------------------------------------------------------------------------
482
483 template <typename T>
484 class optional : private optional_internal::optional_data<T>,
485 private optional_internal::optional_ctor_base<
486 optional_internal::get_ctor_copy_traits<T>()>,
487 private optional_internal::optional_assign_base<
488 optional_internal::get_assign_copy_traits<T>()> {
489 using data_base = optional_internal::optional_data<T>;
490
491 public:
492 typedef T value_type;
493
494 // Constructors
495
496 // Constructs an `optional` holding an empty value, NOT a default constructed
497 // `T`.
498 constexpr optional() noexcept {}
499
500 // Constructs an `optional` initialized with `nullopt` to hold an empty value.
501 constexpr optional(nullopt_t) noexcept {} // NOLINT(runtime/explicit)
502
503 // Copy constructor, standard semantics
504 optional(const optional& src) = default;
505
506 // Move constructor, standard semantics
507 optional(optional&& src) = default;
508
509 // Constructs a non-empty `optional` direct-initialized value of type `T` from
510 // the arguments `std::forward<Args>(args)...` within the `optional`.
511 // (The `in_place_t` is a tag used to indicate that the contained object
512 // should be constructed in-place.)
513 //
514 // TODO(absl-team): Add std::is_constructible<T, Args&&...> SFINAE.
515 template <typename... Args>
516 constexpr explicit optional(in_place_t, Args&&... args)
517 : data_base(in_place_t(), absl::forward<Args>(args)...) {}
518
519 // Constructs a non-empty `optional` direct-initialized value of type `T` from
520 // the arguments of an initializer_list and `std::forward<Args>(args)...`.
521 // (The `in_place_t` is a tag used to indicate that the contained object
522 // should be constructed in-place.)
523 template <typename U, typename... Args,
524 typename = typename std::enable_if<std::is_constructible<
525 T, std::initializer_list<U>&, Args&&...>::value>::type>
526 constexpr explicit optional(in_place_t, std::initializer_list<U> il,
527 Args&&... args)
528 : data_base(in_place_t(), il, absl::forward<Args>(args)...) {
529 }
530
531 // Value constructor (implicit)
532 template <
533 typename U = T,
534 typename std::enable_if<
535 absl::conjunction<absl::negation<std::is_same<
536 in_place_t, typename std::decay<U>::type> >,
537 absl::negation<std::is_same<
538 optional<T>, typename std::decay<U>::type> >,
539 std::is_convertible<U&&, T>,
540 std::is_constructible<T, U&&> >::value,
541 bool>::type = false>
542 constexpr optional(U&& v) : data_base(in_place_t(), absl::forward<U>(v)) {}
543
544 // Value constructor (explicit)
545 template <
546 typename U = T,
547 typename std::enable_if<
548 absl::conjunction<absl::negation<std::is_same<
549 in_place_t, typename std::decay<U>::type>>,
550 absl::negation<std::is_same<
551 optional<T>, typename std::decay<U>::type>>,
552 absl::negation<std::is_convertible<U&&, T>>,
553 std::is_constructible<T, U&&>>::value,
554 bool>::type = false>
555 explicit constexpr optional(U&& v)
556 : data_base(in_place_t(), absl::forward<U>(v)) {}
557
558 // Converting copy constructor (implicit)
559 template <typename U,
560 typename std::enable_if<
561 absl::conjunction<
562 absl::negation<std::is_same<T, U> >,
563 std::is_constructible<T, const U&>,
564 absl::negation<
565 optional_internal::
566 is_constructible_convertible_from_optional<T, U> >,
567 std::is_convertible<const U&, T> >::value,
568 bool>::type = false>
569 optional(const optional<U>& rhs) {
570 if (rhs) {
571 this->construct(*rhs);
572 }
573 }
574
575 // Converting copy constructor (explicit)
576 template <typename U,
577 typename std::enable_if<
578 absl::conjunction<
579 absl::negation<std::is_same<T, U>>,
580 std::is_constructible<T, const U&>,
581 absl::negation<
582 optional_internal::
583 is_constructible_convertible_from_optional<T, U>>,
584 absl::negation<std::is_convertible<const U&, T>>>::value,
585 bool>::type = false>
586 explicit optional(const optional<U>& rhs) {
587 if (rhs) {
588 this->construct(*rhs);
589 }
590 }
591
592 // Converting move constructor (implicit)
593 template <typename U,
594 typename std::enable_if<
595 absl::conjunction<
596 absl::negation<std::is_same<T, U> >,
597 std::is_constructible<T, U&&>,
598 absl::negation<
599 optional_internal::
600 is_constructible_convertible_from_optional<T, U> >,
601 std::is_convertible<U&&, T> >::value,
602 bool>::type = false>
603 optional(optional<U>&& rhs) {
604 if (rhs) {
605 this->construct(std::move(*rhs));
606 }
607 }
608
609 // Converting move constructor (explicit)
610 template <
611 typename U,
612 typename std::enable_if<
613 absl::conjunction<
614 absl::negation<std::is_same<T, U>>, std::is_constructible<T, U&&>,
615 absl::negation<
616 optional_internal::is_constructible_convertible_from_optional<
617 T, U>>,
618 absl::negation<std::is_convertible<U&&, T>>>::value,
619 bool>::type = false>
620 explicit optional(optional<U>&& rhs) {
621 if (rhs) {
622 this->construct(std::move(*rhs));
623 }
624 }
625
626 // Destructor. Trivial if `T` is trivially destructible.
627 ~optional() = default;
628
629 // Assignment Operators
630
631 // Assignment from `nullopt`
632 //
633 // Example:
634 //
635 // struct S { int value; };
636 // optional<S> opt = absl::nullopt; // Could also use opt = { };
637 optional& operator=(nullopt_t) noexcept {
638 this->destruct();
639 return *this;
640 }
641
642 // Copy assignment operator, standard semantics
643 optional& operator=(const optional& src) = default;
644
645 // Move assignment operator, standard semantics
646 optional& operator=(optional&& src) = default;
647
648 // Value assignment operators
649 template <
650 typename U = T,
651 typename = typename std::enable_if<absl::conjunction<
652 absl::negation<
653 std::is_same<optional<T>, typename std::decay<U>::type>>,
654 absl::negation<
655 absl::conjunction<std::is_scalar<T>,
656 std::is_same<T, typename std::decay<U>::type>>>,
657 std::is_constructible<T, U>, std::is_assignable<T&, U>>::value>::type>
658 optional& operator=(U&& v) {
659 this->assign(std::forward<U>(v));
660 return *this;
661 }
662
663 template <
664 typename U,
665 typename = typename std::enable_if<absl::conjunction<
666 absl::negation<std::is_same<T, U>>,
667 std::is_constructible<T, const U&>, std::is_assignable<T&, const U&>,
668 absl::negation<
669 optional_internal::
670 is_constructible_convertible_assignable_from_optional<
671 T, U>>>::value>::type>
672 optional& operator=(const optional<U>& rhs) {
673 if (rhs) {
674 this->assign(*rhs);
675 } else {
676 this->destruct();
677 }
678 return *this;
679 }
680
681 template <typename U,
682 typename = typename std::enable_if<absl::conjunction<
683 absl::negation<std::is_same<T, U>>, std::is_constructible<T, U>,
684 std::is_assignable<T&, U>,
685 absl::negation<
686 optional_internal::
687 is_constructible_convertible_assignable_from_optional<
688 T, U>>>::value>::type>
689 optional& operator=(optional<U>&& rhs) {
690 if (rhs) {
691 this->assign(std::move(*rhs));
692 } else {
693 this->destruct();
694 }
695 return *this;
696 }
697
698 // Modifiers
699
700 // optional::reset()
701 //
702 // Destroys the inner `T` value of an `absl::optional` if one is present.
703 void reset() noexcept { this->destruct(); }
704
705 // optional::emplace()
706 //
707 // (Re)constructs the underlying `T` in-place with the given forwarded
708 // arguments.
709 //
710 // Example:
711 //
712 // optional<Foo> opt;
713 // opt.emplace(arg1,arg2,arg3); // Constructs Foo(arg1,arg2,arg3)
714 //
715 // If the optional is non-empty, and the `args` refer to subobjects of the
716 // current object, then behaviour is undefined, because the current object
717 // will be destructed before the new object is constructed with `args`.
718 template <typename... Args,
719 typename = typename std::enable_if<
720 std::is_constructible<T, Args&&...>::value>::type>
721 T& emplace(Args&&... args) {
722 this->destruct();
723 this->construct(std::forward<Args>(args)...);
724 return reference();
725 }
726
727 // Emplace reconstruction overload for an initializer list and the given
728 // forwarded arguments.
729 //
730 // Example:
731 //
732 // struct Foo {
733 // Foo(std::initializer_list<int>);
734 // };
735 //
736 // optional<Foo> opt;
737 // opt.emplace({1,2,3}); // Constructs Foo({1,2,3})
738 template <typename U, typename... Args,
739 typename = typename std::enable_if<std::is_constructible<
740 T, std::initializer_list<U>&, Args&&...>::value>::type>
741 T& emplace(std::initializer_list<U> il, Args&&... args) {
742 this->destruct();
743 this->construct(il, std::forward<Args>(args)...);
744 return reference();
745 }
746
747 // Swaps
748
749 // Swap, standard semantics
750 void swap(optional& rhs) noexcept(
751 std::is_nothrow_move_constructible<T>::value&&
752 std::is_trivial<T>::value) {
753 if (*this) {
754 if (rhs) {
755 using std::swap;
756 swap(**this, *rhs);
757 } else {
758 rhs.construct(std::move(**this));
759 this->destruct();
760 }
761 } else {
762 if (rhs) {
763 this->construct(std::move(*rhs));
764 rhs.destruct();
765 } else {
766 // No effect (swap(disengaged, disengaged)).
767 }
768 }
769 }
770
771 // Observers
772
773 // optional::operator->()
774 //
775 // Accesses the underlying `T` value's member `m` of an `optional`. If the
776 // `optional` is empty, behavior is undefined.
777 //
778 // If you need myOpt->foo in constexpr, use (*myOpt).foo instead.
779 const T* operator->() const {
780 assert(this->engaged_);
781 return std::addressof(this->data_);
782 }
783 T* operator->() {
784 assert(this->engaged_);
785 return std::addressof(this->data_);
786 }
787
788 // optional::operator*()
789 //
790 // Accesses the underlying `T` value of an `optional`. If the `optional` is
791 // empty, behavior is undefined.
792 constexpr const T& operator*() const & { return reference(); }
793 T& operator*() & {
794 assert(this->engaged_);
795 return reference();
796 }
797 constexpr const T&& operator*() const && {
798 return absl::move(reference());
799 }
800 T&& operator*() && {
801 assert(this->engaged_);
802 return std::move(reference());
803 }
804
805 // optional::operator bool()
806 //
807 // Returns false if and only if the `optional` is empty.
808 //
809 // if (opt) {
810 // // do something with opt.value();
811 // } else {
812 // // opt is empty.
813 // }
814 //
815 constexpr explicit operator bool() const noexcept { return this->engaged_; }
816
817 // optional::has_value()
818 //
819 // Determines whether the `optional` contains a value. Returns `false` if and
820 // only if `*this` is empty.
821 constexpr bool has_value() const noexcept { return this->engaged_; }
822
823 // Suppress bogus warning on MSVC: MSVC complains call to reference() after
824 // throw_bad_optional_access() is unreachable.
825 #ifdef _MSC_VER
826 #pragma warning(push)
827 #pragma warning(disable : 4702)
828 #endif // _MSC_VER
829 // optional::value()
830 //
831 // Returns a reference to an `optional`s underlying value. The constness
832 // and lvalue/rvalue-ness of the `optional` is preserved to the view of
833 // the `T` sub-object. Throws `absl::bad_optional_access` when the `optional`
834 // is empty.
835 constexpr const T& value() const & {
836 return static_cast<bool>(*this)
837 ? reference()
838 : (optional_internal::throw_bad_optional_access(), reference());
839 }
840 T& value() & {
841 return static_cast<bool>(*this)
842 ? reference()
843 : (optional_internal::throw_bad_optional_access(), reference());
844 }
845 T&& value() && { // NOLINT(build/c++11)
846 return std::move(
847 static_cast<bool>(*this)
848 ? reference()
849 : (optional_internal::throw_bad_optional_access(), reference()));
850 }
851 constexpr const T&& value() const && { // NOLINT(build/c++11)
852 return absl::move(
853 static_cast<bool>(*this)
854 ? reference()
855 : (optional_internal::throw_bad_optional_access(), reference()));
856 }
857 #ifdef _MSC_VER
858 #pragma warning(pop)
859 #endif // _MSC_VER
860
861 // optional::value_or()
862 //
863 // Returns either the value of `T` or a passed default `v` if the `optional`
864 // is empty.
865 template <typename U>
866 constexpr T value_or(U&& v) const& {
867 static_assert(std::is_copy_constructible<value_type>::value,
868 "optional<T>::value_or: T must by copy constructible");
869 static_assert(std::is_convertible<U&&, value_type>::value,
870 "optional<T>::value_or: U must be convertible to T");
871 return static_cast<bool>(*this)
872 ? **this
873 : static_cast<T>(absl::forward<U>(v));
874 }
875 template <typename U>
876 T value_or(U&& v) && { // NOLINT(build/c++11)
877 static_assert(std::is_move_constructible<value_type>::value,
878 "optional<T>::value_or: T must by copy constructible");
879 static_assert(std::is_convertible<U&&, value_type>::value,
880 "optional<T>::value_or: U must be convertible to T");
881 return static_cast<bool>(*this) ? std::move(**this)
882 : static_cast<T>(std::forward<U>(v));
883 }
884
885 private:
886 // Private accessors for internal storage viewed as reference to T.
887 constexpr const T& reference() const { return this->data_; }
888 T& reference() { return this->data_; }
889
890 // T constraint checks. You can't have an optional of nullopt_t, in_place_t
891 // or a reference.
892 static_assert(
893 !std::is_same<nullopt_t, typename std::remove_cv<T>::type>::value,
894 "optional<nullopt_t> is not allowed.");
895 static_assert(
896 !std::is_same<in_place_t, typename std::remove_cv<T>::type>::value,
897 "optional<in_place_t> is not allowed.");
898 static_assert(!std::is_reference<T>::value,
899 "optional<reference> is not allowed.");
900 };
901
902 // Non-member functions
903
904 // swap()
905 //
906 // Performs a swap between two `absl::optional` objects, using standard
907 // semantics.
908 //
909 // NOTE: we assume `is_swappable()` is always `true`. A compile error will
910 // result if this is not the case.
911 template <typename T,
912 typename std::enable_if<std::is_move_constructible<T>::value,
913 bool>::type = false>
914 void swap(optional<T>& a, optional<T>& b) noexcept(noexcept(a.swap(b))) {
915 a.swap(b);
916 }
917
918 // make_optional()
919 //
920 // Creates a non-empty `optional<T>` where the type of `T` is deduced. An
921 // `absl::optional` can also be explicitly instantiated with
922 // `make_optional<T>(v)`.
923 //
924 // Note: `make_optional()` constructions may be declared `constexpr` for
925 // trivially copyable types `T`. Non-trivial types require copy elision
926 // support in C++17 for `make_optional` to support `constexpr` on such
927 // non-trivial types.
928 //
929 // Example:
930 //
931 // constexpr absl::optional<int> opt = absl::make_optional(1);
932 // static_assert(opt.value() == 1, "");
933 template <typename T>
934 constexpr optional<typename std::decay<T>::type> make_optional(T&& v) {
935 return optional<typename std::decay<T>::type>(absl::forward<T>(v));
936 }
937
938 template <typename T, typename... Args>
939 constexpr optional<T> make_optional(Args&&... args) {
940 return optional<T>(in_place_t(), absl::forward<Args>(args)...);
941 }
942
943 template <typename T, typename U, typename... Args>
944 constexpr optional<T> make_optional(std::initializer_list<U> il,
945 Args&&... args) {
946 return optional<T>(in_place_t(), il,
947 absl::forward<Args>(args)...);
948 }
949
950 // Relational operators [optional.relops]
951
952 // Empty optionals are considered equal to each other and less than non-empty
953 // optionals. Supports relations between optional<T> and optional<U>, between
954 // optional<T> and U, and between optional<T> and nullopt.
955 //
956 // Note: We're careful to support T having non-bool relationals.
957
958 // Requires: The expression, e.g. "*x == *y" shall be well-formed and its result
959 // shall be convertible to bool.
960 // The C++17 (N4606) "Returns:" statements are translated into
961 // code in an obvious way here, and the original text retained as function docs.
962 // Returns: If bool(x) != bool(y), false; otherwise if bool(x) == false, true;
963 // otherwise *x == *y.
964 template <typename T, typename U>
965 constexpr auto operator==(const optional<T>& x, const optional<U>& y)
966 -> decltype(optional_internal::convertible_to_bool(*x == *y)) {
967 return static_cast<bool>(x) != static_cast<bool>(y)
968 ? false
969 : static_cast<bool>(x) == false ? true
970 : static_cast<bool>(*x == *y);
971 }
972
973 // Returns: If bool(x) != bool(y), true; otherwise, if bool(x) == false, false;
974 // otherwise *x != *y.
975 template <typename T, typename U>
976 constexpr auto operator!=(const optional<T>& x, const optional<U>& y)
977 -> decltype(optional_internal::convertible_to_bool(*x != *y)) {
978 return static_cast<bool>(x) != static_cast<bool>(y)
979 ? true
980 : static_cast<bool>(x) == false ? false
981 : static_cast<bool>(*x != *y);
982 }
983 // Returns: If !y, false; otherwise, if !x, true; otherwise *x < *y.
984 template <typename T, typename U>
985 constexpr auto operator<(const optional<T>& x, const optional<U>& y)
986 -> decltype(optional_internal::convertible_to_bool(*x < *y)) {
987 return !y ? false : !x ? true : static_cast<bool>(*x < *y);
988 }
989 // Returns: If !x, false; otherwise, if !y, true; otherwise *x > *y.
990 template <typename T, typename U>
991 constexpr auto operator>(const optional<T>& x, const optional<U>& y)
992 -> decltype(optional_internal::convertible_to_bool(*x > *y)) {
993 return !x ? false : !y ? true : static_cast<bool>(*x > *y);
994 }
995 // Returns: If !x, true; otherwise, if !y, false; otherwise *x <= *y.
996 template <typename T, typename U>
997 constexpr auto operator<=(const optional<T>& x, const optional<U>& y)
998 -> decltype(optional_internal::convertible_to_bool(*x <= *y)) {
999 return !x ? true : !y ? false : static_cast<bool>(*x <= *y);
1000 }
1001 // Returns: If !y, true; otherwise, if !x, false; otherwise *x >= *y.
1002 template <typename T, typename U>
1003 constexpr auto operator>=(const optional<T>& x, const optional<U>& y)
1004 -> decltype(optional_internal::convertible_to_bool(*x >= *y)) {
1005 return !y ? true : !x ? false : static_cast<bool>(*x >= *y);
1006 }
1007
1008 // Comparison with nullopt [optional.nullops]
1009 // The C++17 (N4606) "Returns:" statements are used directly here.
1010 template <typename T>
1011 constexpr bool operator==(const optional<T>& x, nullopt_t) noexcept {
1012 return !x;
1013 }
1014 template <typename T>
1015 constexpr bool operator==(nullopt_t, const optional<T>& x) noexcept {
1016 return !x;
1017 }
1018 template <typename T>
1019 constexpr bool operator!=(const optional<T>& x, nullopt_t) noexcept {
1020 return static_cast<bool>(x);
1021 }
1022 template <typename T>
1023 constexpr bool operator!=(nullopt_t, const optional<T>& x) noexcept {
1024 return static_cast<bool>(x);
1025 }
1026 template <typename T>
1027 constexpr bool operator<(const optional<T>&, nullopt_t) noexcept {
1028 return false;
1029 }
1030 template <typename T>
1031 constexpr bool operator<(nullopt_t, const optional<T>& x) noexcept {
1032 return static_cast<bool>(x);
1033 }
1034 template <typename T>
1035 constexpr bool operator<=(const optional<T>& x, nullopt_t) noexcept {
1036 return !x;
1037 }
1038 template <typename T>
1039 constexpr bool operator<=(nullopt_t, const optional<T>&) noexcept {
1040 return true;
1041 }
1042 template <typename T>
1043 constexpr bool operator>(const optional<T>& x, nullopt_t) noexcept {
1044 return static_cast<bool>(x);
1045 }
1046 template <typename T>
1047 constexpr bool operator>(nullopt_t, const optional<T>&) noexcept {
1048 return false;
1049 }
1050 template <typename T>
1051 constexpr bool operator>=(const optional<T>&, nullopt_t) noexcept {
1052 return true;
1053 }
1054 template <typename T>
1055 constexpr bool operator>=(nullopt_t, const optional<T>& x) noexcept {
1056 return !x;
1057 }
1058
1059 // Comparison with T [optional.comp_with_t]
1060
1061 // Requires: The expression, e.g. "*x == v" shall be well-formed and its result
1062 // shall be convertible to bool.
1063 // The C++17 (N4606) "Equivalent to:" statements are used directly here.
1064 template <typename T, typename U>
1065 constexpr auto operator==(const optional<T>& x, const U& v)
1066 -> decltype(optional_internal::convertible_to_bool(*x == v)) {
1067 return static_cast<bool>(x) ? static_cast<bool>(*x == v) : false;
1068 }
1069 template <typename T, typename U>
1070 constexpr auto operator==(const U& v, const optional<T>& x)
1071 -> decltype(optional_internal::convertible_to_bool(v == *x)) {
1072 return static_cast<bool>(x) ? static_cast<bool>(v == *x) : false;
1073 }
1074 template <typename T, typename U>
1075 constexpr auto operator!=(const optional<T>& x, const U& v)
1076 -> decltype(optional_internal::convertible_to_bool(*x != v)) {
1077 return static_cast<bool>(x) ? static_cast<bool>(*x != v) : true;
1078 }
1079 template <typename T, typename U>
1080 constexpr auto operator!=(const U& v, const optional<T>& x)
1081 -> decltype(optional_internal::convertible_to_bool(v != *x)) {
1082 return static_cast<bool>(x) ? static_cast<bool>(v != *x) : true;
1083 }
1084 template <typename T, typename U>
1085 constexpr auto operator<(const optional<T>& x, const U& v)
1086 -> decltype(optional_internal::convertible_to_bool(*x < v)) {
1087 return static_cast<bool>(x) ? static_cast<bool>(*x < v) : true;
1088 }
1089 template <typename T, typename U>
1090 constexpr auto operator<(const U& v, const optional<T>& x)
1091 -> decltype(optional_internal::convertible_to_bool(v < *x)) {
1092 return static_cast<bool>(x) ? static_cast<bool>(v < *x) : false;
1093 }
1094 template <typename T, typename U>
1095 constexpr auto operator<=(const optional<T>& x, const U& v)
1096 -> decltype(optional_internal::convertible_to_bool(*x <= v)) {
1097 return static_cast<bool>(x) ? static_cast<bool>(*x <= v) : true;
1098 }
1099 template <typename T, typename U>
1100 constexpr auto operator<=(const U& v, const optional<T>& x)
1101 -> decltype(optional_internal::convertible_to_bool(v <= *x)) {
1102 return static_cast<bool>(x) ? static_cast<bool>(v <= *x) : false;
1103 }
1104 template <typename T, typename U>
1105 constexpr auto operator>(const optional<T>& x, const U& v)
1106 -> decltype(optional_internal::convertible_to_bool(*x > v)) {
1107 return static_cast<bool>(x) ? static_cast<bool>(*x > v) : false;
1108 }
1109 template <typename T, typename U>
1110 constexpr auto operator>(const U& v, const optional<T>& x)
1111 -> decltype(optional_internal::convertible_to_bool(v > *x)) {
1112 return static_cast<bool>(x) ? static_cast<bool>(v > *x) : true;
1113 }
1114 template <typename T, typename U>
1115 constexpr auto operator>=(const optional<T>& x, const U& v)
1116 -> decltype(optional_internal::convertible_to_bool(*x >= v)) {
1117 return static_cast<bool>(x) ? static_cast<bool>(*x >= v) : false;
1118 }
1119 template <typename T, typename U>
1120 constexpr auto operator>=(const U& v, const optional<T>& x)
1121 -> decltype(optional_internal::convertible_to_bool(v >= *x)) {
1122 return static_cast<bool>(x) ? static_cast<bool>(v >= *x) : true;
1123 }
1124
1125 } // namespace absl
1126
1127 namespace std {
1128
1129 // std::hash specialization for absl::optional.
1130 template <typename T>
1131 struct hash<absl::optional<T> >
1132 : absl::optional_internal::optional_hash_base<T> {};
1133
1134 } // namespace std
1135
1136 #undef ABSL_OPTIONAL_USE_INHERITING_CONSTRUCTORS
1137 #undef ABSL_MSVC_CONSTEXPR_BUG_IN_UNION_LIKE_CLASS
1138
1139 #endif // ABSL_HAVE_STD_OPTIONAL
1140
1141 #endif // ABSL_TYPES_OPTIONAL_H_
1142