1// Copyright 2016 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#ifndef BASE_OPTIONAL_H_
6#define BASE_OPTIONAL_H_
7
8#include <functional>
9#include <type_traits>
10#include <utility>
11
12#include "base/logging.h"
13#include "base/template_util.h"
14
15namespace base {
16
17// Specification:
18// http://en.cppreference.com/w/cpp/utility/optional/nullopt_t
19struct nullopt_t {
20 constexpr explicit nullopt_t(int) {}
21};
22
23// Specification:
24// http://en.cppreference.com/w/cpp/utility/optional/nullopt
25constexpr nullopt_t nullopt(0);
26
27// Forward declaration, which is refered by following helpers.
28template <typename T>
29class Optional;
30
31namespace internal {
32
33template <typename T, bool = std::is_trivially_destructible<T>::value>
34struct OptionalStorageBase {
35 // Initializing |empty_| here instead of using default member initializing
36 // to avoid errors in g++ 4.8.
37 constexpr OptionalStorageBase() : empty_('\0') {}
38
39 template <class... Args>
40 constexpr explicit OptionalStorageBase(in_place_t, Args&&... args)
41 : is_populated_(true), value_(std::forward<Args>(args)...) {}
42
43 // When T is not trivially destructible we must call its
44 // destructor before deallocating its memory.
45 // Note that this hides the (implicitly declared) move constructor, which
46 // would be used for constexpr move constructor in OptionalStorage<T>.
47 // It is needed iff T is trivially move constructible. However, the current
48 // is_trivially_{copy,move}_constructible implementation requires
49 // is_trivially_destructible (which looks a bug, cf:
50 // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=51452 and
51 // http://cplusplus.github.io/LWG/lwg-active.html#2116), so it is not
52 // necessary for this case at the moment. Please see also the destructor
53 // comment in "is_trivially_destructible = true" specialization below.
54 ~OptionalStorageBase() {
55 if (is_populated_)
56 value_.~T();
57 }
58
59 template <class... Args>
60 void Init(Args&&... args) {
61 DCHECK(!is_populated_);
62 ::new (&value_) T(std::forward<Args>(args)...);
63 is_populated_ = true;
64 }
65
66 bool is_populated_ = false;
67 union {
68 // |empty_| exists so that the union will always be initialized, even when
69 // it doesn't contain a value. Union members must be initialized for the
70 // constructor to be 'constexpr'.
71 char empty_;
72 T value_;
73 };
74};
75
76template <typename T>
77struct OptionalStorageBase<T, true /* trivially destructible */> {
78 // Initializing |empty_| here instead of using default member initializing
79 // to avoid errors in g++ 4.8.
80 constexpr OptionalStorageBase() : empty_('\0') {}
81
82 template <class... Args>
83 constexpr explicit OptionalStorageBase(in_place_t, Args&&... args)
84 : is_populated_(true), value_(std::forward<Args>(args)...) {}
85
86 // When T is trivially destructible (i.e. its destructor does nothing) there
87 // is no need to call it. Implicitly defined destructor is trivial, because
88 // both members (bool and union containing only variants which are trivially
89 // destructible) are trivially destructible.
90 // Explicitly-defaulted destructor is also trivial, but do not use it here,
91 // because it hides the implicit move constructor. It is needed to implement
92 // constexpr move constructor in OptionalStorage iff T is trivially move
93 // constructible. Note that, if T is trivially move constructible, the move
94 // constructor of OptionalStorageBase<T> is also implicitly defined and it is
95 // trivially move constructor. If T is not trivially move constructible,
96 // "not declaring move constructor without destructor declaration" here means
97 // "delete move constructor", which works because any move constructor of
98 // OptionalStorage will not refer to it in that case.
99
100 template <class... Args>
101 void Init(Args&&... args) {
102 DCHECK(!is_populated_);
103 ::new (&value_) T(std::forward<Args>(args)...);
104 is_populated_ = true;
105 }
106
107 bool is_populated_ = false;
108 union {
109 // |empty_| exists so that the union will always be initialized, even when
110 // it doesn't contain a value. Union members must be initialized for the
111 // constructor to be 'constexpr'.
112 char empty_;
113 T value_;
114 };
115};
116
117// Implement conditional constexpr copy and move constructors. These are
118// constexpr if is_trivially_{copy,move}_constructible<T>::value is true
119// respectively. If each is true, the corresponding constructor is defined as
120// "= default;", which generates a constexpr constructor (In this case,
121// the condition of constexpr-ness is satisfied because the base class also has
122// compiler generated constexpr {copy,move} constructors). Note that
123// placement-new is prohibited in constexpr.
124template <typename T,
125 bool = is_trivially_copy_constructible<T>::value,
126 bool = std::is_trivially_move_constructible<T>::value>
127struct OptionalStorage : OptionalStorageBase<T> {
128 // This is no trivially {copy,move} constructible case. Other cases are
129 // defined below as specializations.
130
131 // Accessing the members of template base class requires explicit
132 // declaration.
133 using OptionalStorageBase<T>::is_populated_;
134 using OptionalStorageBase<T>::value_;
135 using OptionalStorageBase<T>::Init;
136
137 // Inherit constructors (specifically, the in_place constructor).
138 using OptionalStorageBase<T>::OptionalStorageBase;
139
140 // User defined constructor deletes the default constructor.
141 // Define it explicitly.
142 OptionalStorage() = default;
143
144 OptionalStorage(const OptionalStorage& other) : OptionalStorageBase<T>() {
145 if (other.is_populated_)
146 Init(other.value_);
147 }
148
149 OptionalStorage(OptionalStorage&& other) noexcept(
150 std::is_nothrow_move_constructible<T>::value) {
151 if (other.is_populated_)
152 Init(std::move(other.value_));
153 }
154};
155
156template <typename T>
157struct OptionalStorage<T,
158 true /* trivially copy constructible */,
159 false /* trivially move constructible */>
160 : OptionalStorageBase<T> {
161 using OptionalStorageBase<T>::is_populated_;
162 using OptionalStorageBase<T>::value_;
163 using OptionalStorageBase<T>::Init;
164 using OptionalStorageBase<T>::OptionalStorageBase;
165
166 OptionalStorage() = default;
167 OptionalStorage(const OptionalStorage& other) = default;
168
169 OptionalStorage(OptionalStorage&& other) noexcept(
170 std::is_nothrow_move_constructible<T>::value) {
171 if (other.is_populated_)
172 Init(std::move(other.value_));
173 }
174};
175
176template <typename T>
177struct OptionalStorage<T,
178 false /* trivially copy constructible */,
179 true /* trivially move constructible */>
180 : OptionalStorageBase<T> {
181 using OptionalStorageBase<T>::is_populated_;
182 using OptionalStorageBase<T>::value_;
183 using OptionalStorageBase<T>::Init;
184 using OptionalStorageBase<T>::OptionalStorageBase;
185
186 OptionalStorage() = default;
187 OptionalStorage(OptionalStorage&& other) = default;
188
189 OptionalStorage(const OptionalStorage& other) {
190 if (other.is_populated_)
191 Init(other.value_);
192 }
193};
194
195template <typename T>
196struct OptionalStorage<T,
197 true /* trivially copy constructible */,
198 true /* trivially move constructible */>
199 : OptionalStorageBase<T> {
200 // If both trivially {copy,move} constructible are true, it is not necessary
201 // to use user-defined constructors. So, just inheriting constructors
202 // from the base class works.
203 using OptionalStorageBase<T>::OptionalStorageBase;
204};
205
206// Base class to support conditionally usable copy-/move- constructors
207// and assign operators.
208template <typename T>
209class OptionalBase {
210 // This class provides implementation rather than public API, so everything
211 // should be hidden. Often we use composition, but we cannot in this case
212 // because of C++ language restriction.
213 protected:
214 constexpr OptionalBase() = default;
215 constexpr OptionalBase(const OptionalBase& other) = default;
216 constexpr OptionalBase(OptionalBase&& other) = default;
217
218 template <class... Args>
219 constexpr explicit OptionalBase(in_place_t, Args&&... args)
220 : storage_(in_place, std::forward<Args>(args)...) {}
221
222 // Implementation of converting constructors.
223 template <typename U>
224 explicit OptionalBase(const OptionalBase<U>& other) {
225 if (other.storage_.is_populated_)
226 storage_.Init(other.storage_.value_);
227 }
228
229 template <typename U>
230 explicit OptionalBase(OptionalBase<U>&& other) {
231 if (other.storage_.is_populated_)
232 storage_.Init(std::move(other.storage_.value_));
233 }
234
235 ~OptionalBase() = default;
236
237 OptionalBase& operator=(const OptionalBase& other) {
238 CopyAssign(other);
239 return *this;
240 }
241
242 OptionalBase& operator=(OptionalBase&& other) noexcept(
243 std::is_nothrow_move_assignable<T>::value&&
244 std::is_nothrow_move_constructible<T>::value) {
245 MoveAssign(std::move(other));
246 return *this;
247 }
248
249 template <typename U>
250 void CopyAssign(const OptionalBase<U>& other) {
251 if (other.storage_.is_populated_)
252 InitOrAssign(other.storage_.value_);
253 else
254 FreeIfNeeded();
255 }
256
257 template <typename U>
258 void MoveAssign(OptionalBase<U>&& other) {
259 if (other.storage_.is_populated_)
260 InitOrAssign(std::move(other.storage_.value_));
261 else
262 FreeIfNeeded();
263 }
264
265 template <typename U>
266 void InitOrAssign(U&& value) {
267 if (storage_.is_populated_)
268 storage_.value_ = std::forward<U>(value);
269 else
270 storage_.Init(std::forward<U>(value));
271 }
272
273 void FreeIfNeeded() {
274 if (!storage_.is_populated_)
275 return;
276 storage_.value_.~T();
277 storage_.is_populated_ = false;
278 }
279
280 // For implementing conversion, allow access to other typed OptionalBase
281 // class.
282 template <typename U>
283 friend class OptionalBase;
284
285 OptionalStorage<T> storage_;
286};
287
288// The following {Copy,Move}{Constructible,Assignable} structs are helpers to
289// implement constructor/assign-operator overloading. Specifically, if T is
290// is not movable but copyable, Optional<T>'s move constructor should not
291// participate in overload resolution. This inheritance trick implements that.
292template <bool is_copy_constructible>
293struct CopyConstructible {};
294
295template <>
296struct CopyConstructible<false> {
297 constexpr CopyConstructible() = default;
298 constexpr CopyConstructible(const CopyConstructible&) = delete;
299 constexpr CopyConstructible(CopyConstructible&&) = default;
300 CopyConstructible& operator=(const CopyConstructible&) = default;
301 CopyConstructible& operator=(CopyConstructible&&) = default;
302};
303
304template <bool is_move_constructible>
305struct MoveConstructible {};
306
307template <>
308struct MoveConstructible<false> {
309 constexpr MoveConstructible() = default;
310 constexpr MoveConstructible(const MoveConstructible&) = default;
311 constexpr MoveConstructible(MoveConstructible&&) = delete;
312 MoveConstructible& operator=(const MoveConstructible&) = default;
313 MoveConstructible& operator=(MoveConstructible&&) = default;
314};
315
316template <bool is_copy_assignable>
317struct CopyAssignable {};
318
319template <>
320struct CopyAssignable<false> {
321 constexpr CopyAssignable() = default;
322 constexpr CopyAssignable(const CopyAssignable&) = default;
323 constexpr CopyAssignable(CopyAssignable&&) = default;
324 CopyAssignable& operator=(const CopyAssignable&) = delete;
325 CopyAssignable& operator=(CopyAssignable&&) = default;
326};
327
328template <bool is_move_assignable>
329struct MoveAssignable {};
330
331template <>
332struct MoveAssignable<false> {
333 constexpr MoveAssignable() = default;
334 constexpr MoveAssignable(const MoveAssignable&) = default;
335 constexpr MoveAssignable(MoveAssignable&&) = default;
336 MoveAssignable& operator=(const MoveAssignable&) = default;
337 MoveAssignable& operator=(MoveAssignable&&) = delete;
338};
339
340// Helper to conditionally enable converting constructors and assign operators.
341template <typename T, typename U>
342struct IsConvertibleFromOptional
343 : std::integral_constant<
344 bool,
345 std::is_constructible<T, Optional<U>&>::value ||
346 std::is_constructible<T, const Optional<U>&>::value ||
347 std::is_constructible<T, Optional<U>&&>::value ||
348 std::is_constructible<T, const Optional<U>&&>::value ||
349 std::is_convertible<Optional<U>&, T>::value ||
350 std::is_convertible<const Optional<U>&, T>::value ||
351 std::is_convertible<Optional<U>&&, T>::value ||
352 std::is_convertible<const Optional<U>&&, T>::value> {};
353
354template <typename T, typename U>
355struct IsAssignableFromOptional
356 : std::integral_constant<
357 bool,
358 IsConvertibleFromOptional<T, U>::value ||
359 std::is_assignable<T&, Optional<U>&>::value ||
360 std::is_assignable<T&, const Optional<U>&>::value ||
361 std::is_assignable<T&, Optional<U>&&>::value ||
362 std::is_assignable<T&, const Optional<U>&&>::value> {};
363
364// Forward compatibility for C++17.
365// Introduce one more deeper nested namespace to avoid leaking using std::swap.
366namespace swappable_impl {
367using std::swap;
368
369struct IsSwappableImpl {
370 // Tests if swap can be called. Check<T&>(0) returns true_type iff swap
371 // is available for T. Otherwise, Check's overload resolution falls back
372 // to Check(...) declared below thanks to SFINAE, so returns false_type.
373 template <typename T>
374 static auto Check(int)
375 -> decltype(swap(std::declval<T>(), std::declval<T>()), std::true_type());
376
377 template <typename T>
378 static std::false_type Check(...);
379};
380} // namespace swappable_impl
381
382template <typename T>
383struct IsSwappable : decltype(swappable_impl::IsSwappableImpl::Check<T&>(0)) {};
384
385// Forward compatibility for C++20.
386template <typename T>
387using RemoveCvRefT = std::remove_cv_t<std::remove_reference_t<T>>;
388
389} // namespace internal
390
391// On Windows, by default, empty-base class optimization does not work,
392// which means even if the base class is empty struct, it still consumes one
393// byte for its body. __declspec(empty_bases) enables the optimization.
394// cf)
395// https://blogs.msdn.microsoft.com/vcblog/2016/03/30/optimizing-the-layout-of-empty-base-classes-in-vs2015-update-2-3/
396#ifdef OS_WIN
397#define OPTIONAL_DECLSPEC_EMPTY_BASES __declspec(empty_bases)
398#else
399#define OPTIONAL_DECLSPEC_EMPTY_BASES
400#endif
401
402// base::Optional is a Chromium version of the C++17 optional class:
403// std::optional documentation:
404// http://en.cppreference.com/w/cpp/utility/optional
405// Chromium documentation:
406// https://chromium.googlesource.com/chromium/src/+/master/docs/optional.md
407//
408// These are the differences between the specification and the implementation:
409// - Constructors do not use 'constexpr' as it is a C++14 extension.
410// - 'constexpr' might be missing in some places for reasons specified locally.
411// - No exceptions are thrown, because they are banned from Chromium.
412// Marked noexcept for only move constructor and move assign operators.
413// - All the non-members are in the 'base' namespace instead of 'std'.
414//
415// Note that T cannot have a constructor T(Optional<T>) etc. Optional<T> checks
416// T's constructor (specifically via IsConvertibleFromOptional), and in the
417// check whether T can be constructible from Optional<T>, which is recursive
418// so it does not work. As of Feb 2018, std::optional C++17 implementation in
419// both clang and gcc has same limitation. MSVC SFINAE looks to have different
420// behavior, but anyway it reports an error, too.
421template <typename T>
422class OPTIONAL_DECLSPEC_EMPTY_BASES Optional
423 : public internal::OptionalBase<T>,
424 public internal::CopyConstructible<std::is_copy_constructible<T>::value>,
425 public internal::MoveConstructible<std::is_move_constructible<T>::value>,
426 public internal::CopyAssignable<std::is_copy_constructible<T>::value &&
427 std::is_copy_assignable<T>::value>,
428 public internal::MoveAssignable<std::is_move_constructible<T>::value &&
429 std::is_move_assignable<T>::value> {
430 public:
431#undef OPTIONAL_DECLSPEC_EMPTY_BASES
432 using value_type = T;
433
434 // Defer default/copy/move constructor implementation to OptionalBase.
435 constexpr Optional() = default;
436 constexpr Optional(const Optional& other) = default;
437 constexpr Optional(Optional&& other) noexcept(
438 std::is_nothrow_move_constructible<T>::value) = default;
439
440 constexpr Optional(nullopt_t) {} // NOLINT(runtime/explicit)
441
442 // Converting copy constructor. "explicit" only if
443 // std::is_convertible<const U&, T>::value is false. It is implemented by
444 // declaring two almost same constructors, but that condition in enable_if_t
445 // is different, so that either one is chosen, thanks to SFINAE.
446 template <
447 typename U,
448 std::enable_if_t<std::is_constructible<T, const U&>::value &&
449 !internal::IsConvertibleFromOptional<T, U>::value &&
450 std::is_convertible<const U&, T>::value,
451 bool> = false>
452 Optional(const Optional<U>& other) : internal::OptionalBase<T>(other) {}
453
454 template <
455 typename U,
456 std::enable_if_t<std::is_constructible<T, const U&>::value &&
457 !internal::IsConvertibleFromOptional<T, U>::value &&
458 !std::is_convertible<const U&, T>::value,
459 bool> = false>
460 explicit Optional(const Optional<U>& other)
461 : internal::OptionalBase<T>(other) {}
462
463 // Converting move constructor. Similar to converting copy constructor,
464 // declaring two (explicit and non-explicit) constructors.
465 template <
466 typename U,
467 std::enable_if_t<std::is_constructible<T, U&&>::value &&
468 !internal::IsConvertibleFromOptional<T, U>::value &&
469 std::is_convertible<U&&, T>::value,
470 bool> = false>
471 Optional(Optional<U>&& other) : internal::OptionalBase<T>(std::move(other)) {}
472
473 template <
474 typename U,
475 std::enable_if_t<std::is_constructible<T, U&&>::value &&
476 !internal::IsConvertibleFromOptional<T, U>::value &&
477 !std::is_convertible<U&&, T>::value,
478 bool> = false>
479 explicit Optional(Optional<U>&& other)
480 : internal::OptionalBase<T>(std::move(other)) {}
481
482 template <class... Args>
483 constexpr explicit Optional(in_place_t, Args&&... args)
484 : internal::OptionalBase<T>(in_place, std::forward<Args>(args)...) {}
485
486 template <
487 class U,
488 class... Args,
489 class = std::enable_if_t<std::is_constructible<value_type,
490 std::initializer_list<U>&,
491 Args...>::value>>
492 constexpr explicit Optional(in_place_t,
493 std::initializer_list<U> il,
494 Args&&... args)
495 : internal::OptionalBase<T>(in_place, il, std::forward<Args>(args)...) {}
496
497 // Forward value constructor. Similar to converting constructors,
498 // conditionally explicit.
499 template <
500 typename U = value_type,
501 std::enable_if_t<
502 std::is_constructible<T, U&&>::value &&
503 !std::is_same<internal::RemoveCvRefT<U>, in_place_t>::value &&
504 !std::is_same<internal::RemoveCvRefT<U>, Optional<T>>::value &&
505 std::is_convertible<U&&, T>::value,
506 bool> = false>
507 constexpr Optional(U&& value)
508 : internal::OptionalBase<T>(in_place, std::forward<U>(value)) {}
509
510 template <
511 typename U = value_type,
512 std::enable_if_t<
513 std::is_constructible<T, U&&>::value &&
514 !std::is_same<internal::RemoveCvRefT<U>, in_place_t>::value &&
515 !std::is_same<internal::RemoveCvRefT<U>, Optional<T>>::value &&
516 !std::is_convertible<U&&, T>::value,
517 bool> = false>
518 constexpr explicit Optional(U&& value)
519 : internal::OptionalBase<T>(in_place, std::forward<U>(value)) {}
520
521 ~Optional() = default;
522
523 // Defer copy-/move- assign operator implementation to OptionalBase.
524 Optional& operator=(const Optional& other) = default;
525 Optional& operator=(Optional&& other) noexcept(
526 std::is_nothrow_move_assignable<T>::value&&
527 std::is_nothrow_move_constructible<T>::value) = default;
528
529 Optional& operator=(nullopt_t) {
530 FreeIfNeeded();
531 return *this;
532 }
533
534 // Perfect-forwarded assignment.
535 template <typename U>
536 std::enable_if_t<
537 !std::is_same<internal::RemoveCvRefT<U>, Optional<T>>::value &&
538 std::is_constructible<T, U>::value &&
539 std::is_assignable<T&, U>::value &&
540 (!std::is_scalar<T>::value ||
541 !std::is_same<std::decay_t<U>, T>::value),
542 Optional&>
543 operator=(U&& value) {
544 InitOrAssign(std::forward<U>(value));
545 return *this;
546 }
547
548 // Copy assign the state of other.
549 template <typename U>
550 std::enable_if_t<!internal::IsAssignableFromOptional<T, U>::value &&
551 std::is_constructible<T, const U&>::value &&
552 std::is_assignable<T&, const U&>::value,
553 Optional&>
554 operator=(const Optional<U>& other) {
555 CopyAssign(other);
556 return *this;
557 }
558
559 // Move assign the state of other.
560 template <typename U>
561 std::enable_if_t<!internal::IsAssignableFromOptional<T, U>::value &&
562 std::is_constructible<T, U>::value &&
563 std::is_assignable<T&, U>::value,
564 Optional&>
565 operator=(Optional<U>&& other) {
566 MoveAssign(std::move(other));
567 return *this;
568 }
569
570 constexpr const T* operator->() const {
571 CHECK(storage_.is_populated_);
572 return &storage_.value_;
573 }
574
575 constexpr T* operator->() {
576 CHECK(storage_.is_populated_);
577 return &storage_.value_;
578 }
579
580 constexpr const T& operator*() const & {
581 CHECK(storage_.is_populated_);
582 return storage_.value_;
583 }
584
585 constexpr T& operator*() & {
586 CHECK(storage_.is_populated_);
587 return storage_.value_;
588 }
589
590 constexpr const T&& operator*() const && {
591 CHECK(storage_.is_populated_);
592 return std::move(storage_.value_);
593 }
594
595 constexpr T&& operator*() && {
596 CHECK(storage_.is_populated_);
597 return std::move(storage_.value_);
598 }
599
600 constexpr explicit operator bool() const { return storage_.is_populated_; }
601
602 constexpr bool has_value() const { return storage_.is_populated_; }
603
604 constexpr T& value() & {
605 CHECK(storage_.is_populated_);
606 return storage_.value_;
607 }
608
609 constexpr const T& value() const & {
610 CHECK(storage_.is_populated_);
611 return storage_.value_;
612 }
613
614 constexpr T&& value() && {
615 CHECK(storage_.is_populated_);
616 return std::move(storage_.value_);
617 }
618
619 constexpr const T&& value() const && {
620 CHECK(storage_.is_populated_);
621 return std::move(storage_.value_);
622 }
623
624 template <class U>
625 constexpr T value_or(U&& default_value) const& {
626 // TODO(mlamouri): add the following assert when possible:
627 // static_assert(std::is_copy_constructible<T>::value,
628 // "T must be copy constructible");
629 static_assert(std::is_convertible<U, T>::value,
630 "U must be convertible to T");
631 return storage_.is_populated_
632 ? storage_.value_
633 : static_cast<T>(std::forward<U>(default_value));
634 }
635
636 template <class U>
637 constexpr T value_or(U&& default_value) && {
638 // TODO(mlamouri): add the following assert when possible:
639 // static_assert(std::is_move_constructible<T>::value,
640 // "T must be move constructible");
641 static_assert(std::is_convertible<U, T>::value,
642 "U must be convertible to T");
643 return storage_.is_populated_
644 ? std::move(storage_.value_)
645 : static_cast<T>(std::forward<U>(default_value));
646 }
647
648 void swap(Optional& other) {
649 if (!storage_.is_populated_ && !other.storage_.is_populated_)
650 return;
651
652 if (storage_.is_populated_ != other.storage_.is_populated_) {
653 if (storage_.is_populated_) {
654 other.storage_.Init(std::move(storage_.value_));
655 FreeIfNeeded();
656 } else {
657 storage_.Init(std::move(other.storage_.value_));
658 other.FreeIfNeeded();
659 }
660 return;
661 }
662
663 DCHECK(storage_.is_populated_ && other.storage_.is_populated_);
664 using std::swap;
665 swap(**this, *other);
666 }
667
668 void reset() { FreeIfNeeded(); }
669
670 template <class... Args>
671 T& emplace(Args&&... args) {
672 FreeIfNeeded();
673 storage_.Init(std::forward<Args>(args)...);
674 return storage_.value_;
675 }
676
677 template <class U, class... Args>
678 std::enable_if_t<
679 std::is_constructible<T, std::initializer_list<U>&, Args&&...>::value,
680 T&>
681 emplace(std::initializer_list<U> il, Args&&... args) {
682 FreeIfNeeded();
683 storage_.Init(il, std::forward<Args>(args)...);
684 return storage_.value_;
685 }
686
687 private:
688 // Accessing template base class's protected member needs explicit
689 // declaration to do so.
690 using internal::OptionalBase<T>::CopyAssign;
691 using internal::OptionalBase<T>::FreeIfNeeded;
692 using internal::OptionalBase<T>::InitOrAssign;
693 using internal::OptionalBase<T>::MoveAssign;
694 using internal::OptionalBase<T>::storage_;
695};
696
697// Here after defines comparation operators. The definition follows
698// http://en.cppreference.com/w/cpp/utility/optional/operator_cmp
699// while bool() casting is replaced by has_value() to meet the chromium
700// style guide.
701template <class T, class U>
702constexpr bool operator==(const Optional<T>& lhs, const Optional<U>& rhs) {
703 if (lhs.has_value() != rhs.has_value())
704 return false;
705 if (!lhs.has_value())
706 return true;
707 return *lhs == *rhs;
708}
709
710template <class T, class U>
711constexpr bool operator!=(const Optional<T>& lhs, const Optional<U>& rhs) {
712 if (lhs.has_value() != rhs.has_value())
713 return true;
714 if (!lhs.has_value())
715 return false;
716 return *lhs != *rhs;
717}
718
719template <class T, class U>
720constexpr bool operator<(const Optional<T>& lhs, const Optional<U>& rhs) {
721 if (!rhs.has_value())
722 return false;
723 if (!lhs.has_value())
724 return true;
725 return *lhs < *rhs;
726}
727
728template <class T, class U>
729constexpr bool operator<=(const Optional<T>& lhs, const Optional<U>& rhs) {
730 if (!lhs.has_value())
731 return true;
732 if (!rhs.has_value())
733 return false;
734 return *lhs <= *rhs;
735}
736
737template <class T, class U>
738constexpr bool operator>(const Optional<T>& lhs, const Optional<U>& rhs) {
739 if (!lhs.has_value())
740 return false;
741 if (!rhs.has_value())
742 return true;
743 return *lhs > *rhs;
744}
745
746template <class T, class U>
747constexpr bool operator>=(const Optional<T>& lhs, const Optional<U>& rhs) {
748 if (!rhs.has_value())
749 return true;
750 if (!lhs.has_value())
751 return false;
752 return *lhs >= *rhs;
753}
754
755template <class T>
756constexpr bool operator==(const Optional<T>& opt, nullopt_t) {
757 return !opt;
758}
759
760template <class T>
761constexpr bool operator==(nullopt_t, const Optional<T>& opt) {
762 return !opt;
763}
764
765template <class T>
766constexpr bool operator!=(const Optional<T>& opt, nullopt_t) {
767 return opt.has_value();
768}
769
770template <class T>
771constexpr bool operator!=(nullopt_t, const Optional<T>& opt) {
772 return opt.has_value();
773}
774
775template <class T>
776constexpr bool operator<(const Optional<T>& opt, nullopt_t) {
777 return false;
778}
779
780template <class T>
781constexpr bool operator<(nullopt_t, const Optional<T>& opt) {
782 return opt.has_value();
783}
784
785template <class T>
786constexpr bool operator<=(const Optional<T>& opt, nullopt_t) {
787 return !opt;
788}
789
790template <class T>
791constexpr bool operator<=(nullopt_t, const Optional<T>& opt) {
792 return true;
793}
794
795template <class T>
796constexpr bool operator>(const Optional<T>& opt, nullopt_t) {
797 return opt.has_value();
798}
799
800template <class T>
801constexpr bool operator>(nullopt_t, const Optional<T>& opt) {
802 return false;
803}
804
805template <class T>
806constexpr bool operator>=(const Optional<T>& opt, nullopt_t) {
807 return true;
808}
809
810template <class T>
811constexpr bool operator>=(nullopt_t, const Optional<T>& opt) {
812 return !opt;
813}
814
815template <class T, class U>
816constexpr bool operator==(const Optional<T>& opt, const U& value) {
817 return opt.has_value() ? *opt == value : false;
818}
819
820template <class T, class U>
821constexpr bool operator==(const U& value, const Optional<T>& opt) {
822 return opt.has_value() ? value == *opt : false;
823}
824
825template <class T, class U>
826constexpr bool operator!=(const Optional<T>& opt, const U& value) {
827 return opt.has_value() ? *opt != value : true;
828}
829
830template <class T, class U>
831constexpr bool operator!=(const U& value, const Optional<T>& opt) {
832 return opt.has_value() ? value != *opt : true;
833}
834
835template <class T, class U>
836constexpr bool operator<(const Optional<T>& opt, const U& value) {
837 return opt.has_value() ? *opt < value : true;
838}
839
840template <class T, class U>
841constexpr bool operator<(const U& value, const Optional<T>& opt) {
842 return opt.has_value() ? value < *opt : false;
843}
844
845template <class T, class U>
846constexpr bool operator<=(const Optional<T>& opt, const U& value) {
847 return opt.has_value() ? *opt <= value : true;
848}
849
850template <class T, class U>
851constexpr bool operator<=(const U& value, const Optional<T>& opt) {
852 return opt.has_value() ? value <= *opt : false;
853}
854
855template <class T, class U>
856constexpr bool operator>(const Optional<T>& opt, const U& value) {
857 return opt.has_value() ? *opt > value : false;
858}
859
860template <class T, class U>
861constexpr bool operator>(const U& value, const Optional<T>& opt) {
862 return opt.has_value() ? value > *opt : true;
863}
864
865template <class T, class U>
866constexpr bool operator>=(const Optional<T>& opt, const U& value) {
867 return opt.has_value() ? *opt >= value : false;
868}
869
870template <class T, class U>
871constexpr bool operator>=(const U& value, const Optional<T>& opt) {
872 return opt.has_value() ? value >= *opt : true;
873}
874
875template <class T>
876constexpr Optional<std::decay_t<T>> make_optional(T&& value) {
877 return Optional<std::decay_t<T>>(std::forward<T>(value));
878}
879
880template <class T, class... Args>
881constexpr Optional<T> make_optional(Args&&... args) {
882 return Optional<T>(in_place, std::forward<Args>(args)...);
883}
884
885template <class T, class U, class... Args>
886constexpr Optional<T> make_optional(std::initializer_list<U> il,
887 Args&&... args) {
888 return Optional<T>(in_place, il, std::forward<Args>(args)...);
889}
890
891template<typename T>
892constexpr Optional<T> pass_optional(const Optional<T> &opt) {
893 return opt ? make_optional(*opt) : nullopt;
894}
895
896// Partial specialization for a function template is not allowed. Also, it is
897// not allowed to add overload function to std namespace, while it is allowed
898// to specialize the template in std. Thus, swap() (kind of) overloading is
899// defined in base namespace, instead.
900template <class T>
901std::enable_if_t<std::is_move_constructible<T>::value &&
902 internal::IsSwappable<T>::value>
903swap(Optional<T>& lhs, Optional<T>& rhs) {
904 lhs.swap(rhs);
905}
906
907} // namespace base
908
909namespace std {
910
911template <class T>
912struct hash<base::Optional<T>> {
913 size_t operator()(const base::Optional<T>& opt) const {
914 return opt == base::nullopt ? 0 : std::hash<T>()(*opt);
915 }
916};
917
918} // namespace std
919
920#endif // BASE_OPTIONAL_H_
921