blob: c1d11ca7a184fa6bddef466f37993a7474accbd3 [file] [log] [blame]
mlamouri53f6b252016-04-19 17:27:011// 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 <type_traits>
Hidehiko Abe25bbd5e2017-12-20 04:43:079#include <utility>
mlamouri53f6b252016-04-19 17:27:0110
11#include "base/logging.h"
Hidehiko Abe4d8468a2018-02-23 09:50:4112#include "base/template_util.h"
mlamouri53f6b252016-04-19 17:27:0113
14namespace base {
15
16// Specification:
17// http://en.cppreference.com/w/cpp/utility/optional/in_place_t
18struct in_place_t {};
19
20// Specification:
21// http://en.cppreference.com/w/cpp/utility/optional/nullopt_t
22struct nullopt_t {
23 constexpr explicit nullopt_t(int) {}
24};
25
26// Specification:
27// http://en.cppreference.com/w/cpp/utility/optional/in_place
28constexpr in_place_t in_place = {};
29
30// Specification:
31// http://en.cppreference.com/w/cpp/utility/optional/nullopt
32constexpr nullopt_t nullopt(0);
33
Hidehiko Abed39417a52018-01-31 03:22:4234// Forward declaration, which is refered by following helpers.
35template <typename T>
36class Optional;
37
alshabalinf06b07df2016-05-27 08:01:3138namespace internal {
39
danakj90acaf8292017-04-05 17:59:2740template <typename T, bool = std::is_trivially_destructible<T>::value>
Hidehiko Abe5134ab382018-01-08 09:38:1641struct OptionalStorageBase {
alshabalina637f252016-10-26 22:29:2842 // Initializing |empty_| here instead of using default member initializing
43 // to avoid errors in g++ 4.8.
Hidehiko Abe5134ab382018-01-08 09:38:1644 constexpr OptionalStorageBase() : empty_('\0') {}
alshabalin9494e4542016-10-25 09:56:4145
alshabalin9494e4542016-10-25 09:56:4146 template <class... Args>
Hidehiko Abe5134ab382018-01-08 09:38:1647 constexpr explicit OptionalStorageBase(in_place_t, Args&&... args)
Chris Blume0a5dd142018-01-24 22:35:4048 : is_populated_(true), value_(std::forward<Args>(args)...) {}
alshabalin9494e4542016-10-25 09:56:4149
alshabalinf06b07df2016-05-27 08:01:3150 // When T is not trivially destructible we must call its
51 // destructor before deallocating its memory.
Hidehiko Abef1c87892018-01-19 23:50:2452 // Note that this hides the (implicitly declared) move constructor, which
53 // would be used for constexpr move constructor in OptionalStorage<T>.
54 // It is needed iff T is trivially move constructible. However, the current
55 // is_trivially_{copy,move}_constructible implementation requires
56 // is_trivially_destructible (which looks a bug, cf:
57 // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=51452 and
58 // http://cplusplus.github.io/LWG/lwg-active.html#2116), so it is not
59 // necessary for this case at the moment. Please see also the destructor
60 // comment in "is_trivially_destructible = true" specialization below.
Hidehiko Abe5134ab382018-01-08 09:38:1661 ~OptionalStorageBase() {
Chris Blume0a5dd142018-01-24 22:35:4062 if (is_populated_)
kwiberg882859a2016-08-16 09:42:2163 value_.~T();
alshabalinf06b07df2016-05-27 08:01:3164 }
65
Hidehiko Abe5134ab382018-01-08 09:38:1666 template <class... Args>
67 void Init(Args&&... args) {
Chris Blume0a5dd142018-01-24 22:35:4068 DCHECK(!is_populated_);
Hidehiko Abe5134ab382018-01-08 09:38:1669 ::new (&value_) T(std::forward<Args>(args)...);
Chris Blume0a5dd142018-01-24 22:35:4070 is_populated_ = true;
Hidehiko Abe5134ab382018-01-08 09:38:1671 }
72
Chris Blume0a5dd142018-01-24 22:35:4073 bool is_populated_ = false;
kwiberg882859a2016-08-16 09:42:2174 union {
75 // |empty_| exists so that the union will always be initialized, even when
alshabalina637f252016-10-26 22:29:2876 // it doesn't contain a value. Union members must be initialized for the
77 // constructor to be 'constexpr'.
78 char empty_;
kwiberg882859a2016-08-16 09:42:2179 T value_;
80 };
alshabalinf06b07df2016-05-27 08:01:3181};
82
83template <typename T>
Hidehiko Abe5134ab382018-01-08 09:38:1684struct OptionalStorageBase<T, true /* trivially destructible */> {
alshabalina637f252016-10-26 22:29:2885 // Initializing |empty_| here instead of using default member initializing
86 // to avoid errors in g++ 4.8.
Hidehiko Abe5134ab382018-01-08 09:38:1687 constexpr OptionalStorageBase() : empty_('\0') {}
alshabalin9494e4542016-10-25 09:56:4188
alshabalin9494e4542016-10-25 09:56:4189 template <class... Args>
Hidehiko Abe5134ab382018-01-08 09:38:1690 constexpr explicit OptionalStorageBase(in_place_t, Args&&... args)
Chris Blume0a5dd142018-01-24 22:35:4091 : is_populated_(true), value_(std::forward<Args>(args)...) {}
alshabalin9494e4542016-10-25 09:56:4192
kwiberg882859a2016-08-16 09:42:2193 // When T is trivially destructible (i.e. its destructor does nothing) there
Hidehiko Abef1c87892018-01-19 23:50:2494 // is no need to call it. Implicitly defined destructor is trivial, because
95 // both members (bool and union containing only variants which are trivially
96 // destructible) are trivially destructible.
97 // Explicitly-defaulted destructor is also trivial, but do not use it here,
98 // because it hides the implicit move constructor. It is needed to implement
99 // constexpr move constructor in OptionalStorage iff T is trivially move
100 // constructible. Note that, if T is trivially move constructible, the move
101 // constructor of OptionalStorageBase<T> is also implicitly defined and it is
102 // trivially move constructor. If T is not trivially move constructible,
103 // "not declaring move constructor without destructor declaration" here means
104 // "delete move constructor", which works because any move constructor of
105 // OptionalStorage will not refer to it in that case.
Hidehiko Abe5134ab382018-01-08 09:38:16106
107 template <class... Args>
108 void Init(Args&&... args) {
Chris Blume0a5dd142018-01-24 22:35:40109 DCHECK(!is_populated_);
Hidehiko Abe5134ab382018-01-08 09:38:16110 ::new (&value_) T(std::forward<Args>(args)...);
Chris Blume0a5dd142018-01-24 22:35:40111 is_populated_ = true;
Hidehiko Abe5134ab382018-01-08 09:38:16112 }
alshabalinf06b07df2016-05-27 08:01:31113
Chris Blume0a5dd142018-01-24 22:35:40114 bool is_populated_ = false;
kwiberg882859a2016-08-16 09:42:21115 union {
116 // |empty_| exists so that the union will always be initialized, even when
alshabalina637f252016-10-26 22:29:28117 // it doesn't contain a value. Union members must be initialized for the
118 // constructor to be 'constexpr'.
119 char empty_;
kwiberg882859a2016-08-16 09:42:21120 T value_;
121 };
alshabalinf06b07df2016-05-27 08:01:31122};
123
Hidehiko Abe5134ab382018-01-08 09:38:16124// Implement conditional constexpr copy and move constructors. These are
125// constexpr if is_trivially_{copy,move}_constructible<T>::value is true
126// respectively. If each is true, the corresponding constructor is defined as
127// "= default;", which generates a constexpr constructor (In this case,
128// the condition of constexpr-ness is satisfied because the base class also has
129// compiler generated constexpr {copy,move} constructors). Note that
130// placement-new is prohibited in constexpr.
131template <typename T,
Hidehiko Abe4d8468a2018-02-23 09:50:41132 bool = is_trivially_copy_constructible<T>::value,
Hidehiko Abe5134ab382018-01-08 09:38:16133 bool = std::is_trivially_move_constructible<T>::value>
134struct OptionalStorage : OptionalStorageBase<T> {
135 // This is no trivially {copy,move} constructible case. Other cases are
136 // defined below as specializations.
137
138 // Accessing the members of template base class requires explicit
139 // declaration.
Chris Blume0a5dd142018-01-24 22:35:40140 using OptionalStorageBase<T>::is_populated_;
Hidehiko Abe5134ab382018-01-08 09:38:16141 using OptionalStorageBase<T>::value_;
142 using OptionalStorageBase<T>::Init;
143
144 // Inherit constructors (specifically, the in_place constructor).
145 using OptionalStorageBase<T>::OptionalStorageBase;
146
147 // User defined constructor deletes the default constructor.
148 // Define it explicitly.
149 OptionalStorage() = default;
150
151 OptionalStorage(const OptionalStorage& other) {
Chris Blume0a5dd142018-01-24 22:35:40152 if (other.is_populated_)
Hidehiko Abe5134ab382018-01-08 09:38:16153 Init(other.value_);
154 }
155
Fyodor Gayokho65eb2ba2018-03-22 18:09:21156 OptionalStorage(OptionalStorage&& other) noexcept(
157 std::is_nothrow_move_constructible<T>::value) {
Chris Blume0a5dd142018-01-24 22:35:40158 if (other.is_populated_)
Hidehiko Abe5134ab382018-01-08 09:38:16159 Init(std::move(other.value_));
160 }
161};
162
163template <typename T>
164struct OptionalStorage<T,
165 true /* trivially copy constructible */,
166 false /* trivially move constructible */>
167 : OptionalStorageBase<T> {
Chris Blume0a5dd142018-01-24 22:35:40168 using OptionalStorageBase<T>::is_populated_;
Hidehiko Abe5134ab382018-01-08 09:38:16169 using OptionalStorageBase<T>::value_;
170 using OptionalStorageBase<T>::Init;
171 using OptionalStorageBase<T>::OptionalStorageBase;
172
173 OptionalStorage() = default;
174 OptionalStorage(const OptionalStorage& other) = default;
175
Fyodor Gayokho65eb2ba2018-03-22 18:09:21176 OptionalStorage(OptionalStorage&& other) noexcept(
177 std::is_nothrow_move_constructible<T>::value) {
Chris Blume0a5dd142018-01-24 22:35:40178 if (other.is_populated_)
Hidehiko Abe5134ab382018-01-08 09:38:16179 Init(std::move(other.value_));
180 }
181};
182
183template <typename T>
184struct OptionalStorage<T,
185 false /* trivially copy constructible */,
186 true /* trivially move constructible */>
187 : OptionalStorageBase<T> {
Chris Blume0a5dd142018-01-24 22:35:40188 using OptionalStorageBase<T>::is_populated_;
Hidehiko Abe5134ab382018-01-08 09:38:16189 using OptionalStorageBase<T>::value_;
190 using OptionalStorageBase<T>::Init;
191 using OptionalStorageBase<T>::OptionalStorageBase;
192
193 OptionalStorage() = default;
194 OptionalStorage(OptionalStorage&& other) = default;
195
196 OptionalStorage(const OptionalStorage& other) {
Chris Blume0a5dd142018-01-24 22:35:40197 if (other.is_populated_)
Hidehiko Abe5134ab382018-01-08 09:38:16198 Init(other.value_);
199 }
200};
201
202template <typename T>
203struct OptionalStorage<T,
204 true /* trivially copy constructible */,
205 true /* trivially move constructible */>
206 : OptionalStorageBase<T> {
207 // If both trivially {copy,move} constructible are true, it is not necessary
208 // to use user-defined constructors. So, just inheriting constructors
209 // from the base class works.
210 using OptionalStorageBase<T>::OptionalStorageBase;
211};
212
Hidehiko Abe25bbd5e2017-12-20 04:43:07213// Base class to support conditionally usable copy-/move- constructors
214// and assign operators.
215template <typename T>
216class OptionalBase {
217 // This class provides implementation rather than public API, so everything
218 // should be hidden. Often we use composition, but we cannot in this case
219 // because of C++ language restriction.
220 protected:
221 constexpr OptionalBase() = default;
Hidehiko Abe5134ab382018-01-08 09:38:16222 constexpr OptionalBase(const OptionalBase& other) = default;
223 constexpr OptionalBase(OptionalBase&& other) = default;
Hidehiko Abe25bbd5e2017-12-20 04:43:07224
225 template <class... Args>
226 constexpr explicit OptionalBase(in_place_t, Args&&... args)
227 : storage_(in_place, std::forward<Args>(args)...) {}
228
Hidehiko Abed39417a52018-01-31 03:22:42229 // Implementation of converting constructors.
230 template <typename U>
231 explicit OptionalBase(const OptionalBase<U>& other) {
232 if (other.storage_.is_populated_)
233 storage_.Init(other.storage_.value_);
234 }
235
236 template <typename U>
237 explicit OptionalBase(OptionalBase<U>&& other) {
238 if (other.storage_.is_populated_)
239 storage_.Init(std::move(other.storage_.value_));
240 }
241
Hidehiko Abe25bbd5e2017-12-20 04:43:07242 ~OptionalBase() = default;
243
244 OptionalBase& operator=(const OptionalBase& other) {
Hidehiko Abe40ee4ae2018-02-23 04:24:12245 CopyAssign(other);
Hidehiko Abe25bbd5e2017-12-20 04:43:07246 return *this;
247 }
248
Hidehiko Abe3aa61df2018-02-24 12:47:07249 OptionalBase& operator=(OptionalBase&& other) noexcept(
250 std::is_nothrow_move_assignable<T>::value&&
251 std::is_nothrow_move_constructible<T>::value) {
Hidehiko Abe40ee4ae2018-02-23 04:24:12252 MoveAssign(std::move(other));
Hidehiko Abe25bbd5e2017-12-20 04:43:07253 return *this;
254 }
255
Hidehiko Abe40ee4ae2018-02-23 04:24:12256 template <typename U>
257 void CopyAssign(const OptionalBase<U>& other) {
258 if (other.storage_.is_populated_)
259 InitOrAssign(other.storage_.value_);
Hidehiko Abe25bbd5e2017-12-20 04:43:07260 else
Hidehiko Abe40ee4ae2018-02-23 04:24:12261 FreeIfNeeded();
Hidehiko Abe25bbd5e2017-12-20 04:43:07262 }
263
Hidehiko Abe40ee4ae2018-02-23 04:24:12264 template <typename U>
265 void MoveAssign(OptionalBase<U>&& other) {
266 if (other.storage_.is_populated_)
267 InitOrAssign(std::move(other.storage_.value_));
Hidehiko Abe25bbd5e2017-12-20 04:43:07268 else
Hidehiko Abe40ee4ae2018-02-23 04:24:12269 FreeIfNeeded();
270 }
271
272 template <typename U>
273 void InitOrAssign(U&& value) {
274 if (storage_.is_populated_)
275 storage_.value_ = std::forward<U>(value);
276 else
277 storage_.Init(std::forward<U>(value));
Hidehiko Abe25bbd5e2017-12-20 04:43:07278 }
279
280 void FreeIfNeeded() {
Chris Blume0a5dd142018-01-24 22:35:40281 if (!storage_.is_populated_)
Hidehiko Abe25bbd5e2017-12-20 04:43:07282 return;
283 storage_.value_.~T();
Chris Blume0a5dd142018-01-24 22:35:40284 storage_.is_populated_ = false;
Hidehiko Abe25bbd5e2017-12-20 04:43:07285 }
286
Hidehiko Abed39417a52018-01-31 03:22:42287 // For implementing conversion, allow access to other typed OptionalBase
288 // class.
289 template <typename U>
290 friend class OptionalBase;
291
Hidehiko Abe25bbd5e2017-12-20 04:43:07292 OptionalStorage<T> storage_;
293};
294
Hidehiko Abe5cae9642018-01-26 18:01:11295// The following {Copy,Move}{Constructible,Assignable} structs are helpers to
296// implement constructor/assign-operator overloading. Specifically, if T is
297// is not movable but copyable, Optional<T>'s move constructor should not
298// participate in overload resolution. This inheritance trick implements that.
299template <bool is_copy_constructible>
300struct CopyConstructible {};
301
302template <>
303struct CopyConstructible<false> {
304 constexpr CopyConstructible() = default;
305 constexpr CopyConstructible(const CopyConstructible&) = delete;
306 constexpr CopyConstructible(CopyConstructible&&) = default;
307 CopyConstructible& operator=(const CopyConstructible&) = default;
308 CopyConstructible& operator=(CopyConstructible&&) = default;
309};
310
311template <bool is_move_constructible>
312struct MoveConstructible {};
313
314template <>
315struct MoveConstructible<false> {
316 constexpr MoveConstructible() = default;
317 constexpr MoveConstructible(const MoveConstructible&) = default;
318 constexpr MoveConstructible(MoveConstructible&&) = delete;
319 MoveConstructible& operator=(const MoveConstructible&) = default;
320 MoveConstructible& operator=(MoveConstructible&&) = default;
321};
322
323template <bool is_copy_assignable>
324struct CopyAssignable {};
325
326template <>
327struct CopyAssignable<false> {
328 constexpr CopyAssignable() = default;
329 constexpr CopyAssignable(const CopyAssignable&) = default;
330 constexpr CopyAssignable(CopyAssignable&&) = default;
331 CopyAssignable& operator=(const CopyAssignable&) = delete;
332 CopyAssignable& operator=(CopyAssignable&&) = default;
333};
334
335template <bool is_move_assignable>
336struct MoveAssignable {};
337
338template <>
339struct MoveAssignable<false> {
340 constexpr MoveAssignable() = default;
341 constexpr MoveAssignable(const MoveAssignable&) = default;
342 constexpr MoveAssignable(MoveAssignable&&) = default;
343 MoveAssignable& operator=(const MoveAssignable&) = default;
344 MoveAssignable& operator=(MoveAssignable&&) = delete;
345};
346
Hidehiko Abe40ee4ae2018-02-23 04:24:12347// Helper to conditionally enable converting constructors and assign operators.
Hidehiko Abed39417a52018-01-31 03:22:42348template <typename T, typename U>
349struct IsConvertibleFromOptional
350 : std::integral_constant<
351 bool,
352 std::is_constructible<T, Optional<U>&>::value ||
353 std::is_constructible<T, const Optional<U>&>::value ||
354 std::is_constructible<T, Optional<U>&&>::value ||
355 std::is_constructible<T, const Optional<U>&&>::value ||
356 std::is_convertible<Optional<U>&, T>::value ||
357 std::is_convertible<const Optional<U>&, T>::value ||
358 std::is_convertible<Optional<U>&&, T>::value ||
359 std::is_convertible<const Optional<U>&&, T>::value> {};
360
Hidehiko Abe40ee4ae2018-02-23 04:24:12361template <typename T, typename U>
362struct IsAssignableFromOptional
363 : std::integral_constant<
364 bool,
365 IsConvertibleFromOptional<T, U>::value ||
366 std::is_assignable<T&, Optional<U>&>::value ||
367 std::is_assignable<T&, const Optional<U>&>::value ||
368 std::is_assignable<T&, Optional<U>&&>::value ||
369 std::is_assignable<T&, const Optional<U>&&>::value> {};
370
Hidehiko Abeb467afe2018-02-23 07:01:30371// Forward compatibility for C++17.
372// Introduce one more deeper nested namespace to avoid leaking using std::swap.
373namespace swappable_impl {
374using std::swap;
375
376struct IsSwappableImpl {
377 // Tests if swap can be called. Check<T&>(0) returns true_type iff swap
378 // is available for T. Otherwise, Check's overload resolution falls back
379 // to Check(...) declared below thanks to SFINAE, so returns false_type.
380 template <typename T>
381 static auto Check(int)
382 -> decltype(swap(std::declval<T>(), std::declval<T>()), std::true_type());
383
384 template <typename T>
385 static std::false_type Check(...);
386};
387} // namespace swappable_impl
388
389template <typename T>
390struct IsSwappable : decltype(swappable_impl::IsSwappableImpl::Check<T&>(0)) {};
391
Hidehiko Abe14f92bee2018-02-21 06:01:28392// Forward compatibility for C++20.
393template <typename T>
394using RemoveCvRefT = std::remove_cv_t<std::remove_reference_t<T>>;
395
alshabalinf06b07df2016-05-27 08:01:31396} // namespace internal
397
Hidehiko Abec4aa16b2018-03-07 03:45:37398// On Windows, by default, empty-base class optimization does not work,
399// which means even if the base class is empty struct, it still consumes one
400// byte for its body. __declspec(empty_bases) enables the optimization.
401// cf)
402// https://blogs.msdn.microsoft.com/vcblog/2016/03/30/optimizing-the-layout-of-empty-base-classes-in-vs2015-update-2-3/
403#ifdef OS_WIN
404#define OPTIONAL_DECLSPEC_EMPTY_BASES __declspec(empty_bases)
405#else
406#define OPTIONAL_DECLSPEC_EMPTY_BASES
407#endif
408
mlamouri53f6b252016-04-19 17:27:01409// base::Optional is a Chromium version of the C++17 optional class:
410// std::optional documentation:
411// http://en.cppreference.com/w/cpp/utility/optional
412// Chromium documentation:
413// https://chromium.googlesource.com/chromium/src/+/master/docs/optional.md
414//
415// These are the differences between the specification and the implementation:
mlamouri53f6b252016-04-19 17:27:01416// - Constructors do not use 'constexpr' as it is a C++14 extension.
417// - 'constexpr' might be missing in some places for reasons specified locally.
418// - No exceptions are thrown, because they are banned from Chromium.
Hidehiko Abe3aa61df2018-02-24 12:47:07419// Marked noexcept for only move constructor and move assign operators.
mlamouri53f6b252016-04-19 17:27:01420// - All the non-members are in the 'base' namespace instead of 'std'.
Hidehiko Abe14f92bee2018-02-21 06:01:28421//
422// Note that T cannot have a constructor T(Optional<T>) etc. Optional<T> checks
423// T's constructor (specifically via IsConvertibleFromOptional), and in the
424// check whether T can be constructible from Optional<T>, which is recursive
425// so it does not work. As of Feb 2018, std::optional C++17 implementation in
426// both clang and gcc has same limitation. MSVC SFINAE looks to have different
427// behavior, but anyway it reports an error, too.
mlamouri53f6b252016-04-19 17:27:01428template <typename T>
Hidehiko Abec4aa16b2018-03-07 03:45:37429class OPTIONAL_DECLSPEC_EMPTY_BASES Optional
Hidehiko Abe5cae9642018-01-26 18:01:11430 : public internal::OptionalBase<T>,
431 public internal::CopyConstructible<std::is_copy_constructible<T>::value>,
432 public internal::MoveConstructible<std::is_move_constructible<T>::value>,
433 public internal::CopyAssignable<std::is_copy_constructible<T>::value &&
434 std::is_copy_assignable<T>::value>,
435 public internal::MoveAssignable<std::is_move_constructible<T>::value &&
436 std::is_move_assignable<T>::value> {
mlamouri53f6b252016-04-19 17:27:01437 public:
Hidehiko Abec4aa16b2018-03-07 03:45:37438#undef OPTIONAL_DECLSPEC_EMPTY_BASES
alshabalinf06b07df2016-05-27 08:01:31439 using value_type = T;
440
Hidehiko Abe25bbd5e2017-12-20 04:43:07441 // Defer default/copy/move constructor implementation to OptionalBase.
Chris Watkins091d6292017-12-13 04:25:58442 constexpr Optional() = default;
Hidehiko Abe5134ab382018-01-08 09:38:16443 constexpr Optional(const Optional& other) = default;
Hidehiko Abe3aa61df2018-02-24 12:47:07444 constexpr Optional(Optional&& other) noexcept(
445 std::is_nothrow_move_constructible<T>::value) = default;
alshabalin9494e4542016-10-25 09:56:41446
Hidehiko Abed39417a52018-01-31 03:22:42447 constexpr Optional(nullopt_t) {} // NOLINT(runtime/explicit)
448
449 // Converting copy constructor. "explicit" only if
450 // std::is_convertible<const U&, T>::value is false. It is implemented by
451 // declaring two almost same constructors, but that condition in enable_if_t
452 // is different, so that either one is chosen, thanks to SFINAE.
453 template <
454 typename U,
455 std::enable_if_t<std::is_constructible<T, const U&>::value &&
456 !internal::IsConvertibleFromOptional<T, U>::value &&
457 std::is_convertible<const U&, T>::value,
458 bool> = false>
459 Optional(const Optional<U>& other) : internal::OptionalBase<T>(other) {}
460
461 template <
462 typename U,
463 std::enable_if_t<std::is_constructible<T, const U&>::value &&
464 !internal::IsConvertibleFromOptional<T, U>::value &&
465 !std::is_convertible<const U&, T>::value,
466 bool> = false>
467 explicit Optional(const Optional<U>& other)
468 : internal::OptionalBase<T>(other) {}
469
470 // Converting move constructor. Similar to converting copy constructor,
471 // declaring two (explicit and non-explicit) constructors.
472 template <
473 typename U,
474 std::enable_if_t<std::is_constructible<T, U&&>::value &&
475 !internal::IsConvertibleFromOptional<T, U>::value &&
476 std::is_convertible<U&&, T>::value,
477 bool> = false>
478 Optional(Optional<U>&& other) : internal::OptionalBase<T>(std::move(other)) {}
479
480 template <
481 typename U,
482 std::enable_if_t<std::is_constructible<T, U&&>::value &&
483 !internal::IsConvertibleFromOptional<T, U>::value &&
484 !std::is_convertible<U&&, T>::value,
485 bool> = false>
486 explicit Optional(Optional<U>&& other)
487 : internal::OptionalBase<T>(std::move(other)) {}
mlamouri53f6b252016-04-19 17:27:01488
mlamouri53f6b252016-04-19 17:27:01489 template <class... Args>
Hidehiko Abe25bbd5e2017-12-20 04:43:07490 constexpr explicit Optional(in_place_t, Args&&... args)
491 : internal::OptionalBase<T>(in_place, std::forward<Args>(args)...) {}
mlamouri53f6b252016-04-19 17:27:01492
jdoerrieb6e6c752018-01-03 09:13:45493 template <
494 class U,
495 class... Args,
496 class = std::enable_if_t<std::is_constructible<value_type,
497 std::initializer_list<U>&,
498 Args...>::value>>
499 constexpr explicit Optional(in_place_t,
500 std::initializer_list<U> il,
501 Args&&... args)
502 : internal::OptionalBase<T>(in_place, il, std::forward<Args>(args)...) {}
503
Hidehiko Abe14f92bee2018-02-21 06:01:28504 // Forward value constructor. Similar to converting constructors,
505 // conditionally explicit.
506 template <
507 typename U = value_type,
508 std::enable_if_t<
509 std::is_constructible<T, U&&>::value &&
510 !std::is_same<internal::RemoveCvRefT<U>, in_place_t>::value &&
511 !std::is_same<internal::RemoveCvRefT<U>, Optional<T>>::value &&
512 std::is_convertible<U&&, T>::value,
513 bool> = false>
514 constexpr Optional(U&& value)
515 : internal::OptionalBase<T>(in_place, std::forward<U>(value)) {}
516
517 template <
518 typename U = value_type,
519 std::enable_if_t<
520 std::is_constructible<T, U&&>::value &&
521 !std::is_same<internal::RemoveCvRefT<U>, in_place_t>::value &&
522 !std::is_same<internal::RemoveCvRefT<U>, Optional<T>>::value &&
523 !std::is_convertible<U&&, T>::value,
524 bool> = false>
525 constexpr explicit Optional(U&& value)
526 : internal::OptionalBase<T>(in_place, std::forward<U>(value)) {}
527
alshabalinf06b07df2016-05-27 08:01:31528 ~Optional() = default;
mlamouri53f6b252016-04-19 17:27:01529
Hidehiko Abe25bbd5e2017-12-20 04:43:07530 // Defer copy-/move- assign operator implementation to OptionalBase.
Hidehiko Abe25bbd5e2017-12-20 04:43:07531 Optional& operator=(const Optional& other) = default;
Hidehiko Abe3aa61df2018-02-24 12:47:07532 Optional& operator=(Optional&& other) noexcept(
533 std::is_nothrow_move_assignable<T>::value&&
534 std::is_nothrow_move_constructible<T>::value) = default;
Hidehiko Abe25bbd5e2017-12-20 04:43:07535
536 Optional& operator=(nullopt_t) {
mlamouri53f6b252016-04-19 17:27:01537 FreeIfNeeded();
538 return *this;
539 }
540
Hidehiko Abe40ee4ae2018-02-23 04:24:12541 // Perfect-forwarded assignment.
542 template <typename U>
543 std::enable_if_t<
544 !std::is_same<internal::RemoveCvRefT<U>, Optional<T>>::value &&
545 std::is_constructible<T, U>::value &&
546 std::is_assignable<T&, U>::value &&
547 (!std::is_scalar<T>::value ||
548 !std::is_same<std::decay_t<U>, T>::value),
549 Optional&>
mlamouri53f6b252016-04-19 17:27:01550 operator=(U&& value) {
551 InitOrAssign(std::forward<U>(value));
552 return *this;
553 }
554
Hidehiko Abe40ee4ae2018-02-23 04:24:12555 // Copy assign the state of other.
556 template <typename U>
557 std::enable_if_t<!internal::IsAssignableFromOptional<T, U>::value &&
558 std::is_constructible<T, const U&>::value &&
559 std::is_assignable<T&, const U&>::value,
560 Optional&>
561 operator=(const Optional<U>& other) {
562 CopyAssign(other);
563 return *this;
564 }
565
566 // Move assign the state of other.
567 template <typename U>
568 std::enable_if_t<!internal::IsAssignableFromOptional<T, U>::value &&
569 std::is_constructible<T, U>::value &&
570 std::is_assignable<T&, U>::value,
571 Optional&>
572 operator=(Optional<U>&& other) {
573 MoveAssign(std::move(other));
574 return *this;
575 }
576
jdoerriec85bfab2018-04-12 15:01:30577 constexpr const T* operator->() const {
578 CHECK(storage_.is_populated_);
579 return &storage_.value_;
580 }
mlamouri53f6b252016-04-19 17:27:01581
jdoerriec85bfab2018-04-12 15:01:30582 constexpr T* operator->() {
583 CHECK(storage_.is_populated_);
584 return &storage_.value_;
585 }
mlamouri53f6b252016-04-19 17:27:01586
jdoerriec85bfab2018-04-12 15:01:30587 constexpr const T& operator*() const & {
588 CHECK(storage_.is_populated_);
589 return storage_.value_;
590 }
mlamouri53f6b252016-04-19 17:27:01591
jdoerriec85bfab2018-04-12 15:01:30592 constexpr T& operator*() & {
593 CHECK(storage_.is_populated_);
594 return storage_.value_;
595 }
mlamouri53f6b252016-04-19 17:27:01596
jdoerriec85bfab2018-04-12 15:01:30597 constexpr const T&& operator*() const && {
598 CHECK(storage_.is_populated_);
599 return std::move(storage_.value_);
600 }
mlamouri53f6b252016-04-19 17:27:01601
jdoerriec85bfab2018-04-12 15:01:30602 constexpr T&& operator*() && {
603 CHECK(storage_.is_populated_);
604 return std::move(storage_.value_);
605 }
mlamouri53f6b252016-04-19 17:27:01606
Chris Blume0a5dd142018-01-24 22:35:40607 constexpr explicit operator bool() const { return storage_.is_populated_; }
mlamouri53f6b252016-04-19 17:27:01608
Chris Blume0a5dd142018-01-24 22:35:40609 constexpr bool has_value() const { return storage_.is_populated_; }
mlamouri26204572016-08-10 12:24:15610
Daniel Cheng429dbdc52017-10-04 15:33:56611 constexpr T& value() & {
jdoerriec85bfab2018-04-12 15:01:30612 CHECK(storage_.is_populated_);
kwiberg882859a2016-08-16 09:42:21613 return storage_.value_;
mlamouri53f6b252016-04-19 17:27:01614 }
615
Daniel Cheng429dbdc52017-10-04 15:33:56616 constexpr const T& value() const & {
jdoerriec85bfab2018-04-12 15:01:30617 CHECK(storage_.is_populated_);
kwiberg882859a2016-08-16 09:42:21618 return storage_.value_;
mlamouri53f6b252016-04-19 17:27:01619 }
620
Daniel Cheng429dbdc52017-10-04 15:33:56621 constexpr T&& value() && {
jdoerriec85bfab2018-04-12 15:01:30622 CHECK(storage_.is_populated_);
kwiberg882859a2016-08-16 09:42:21623 return std::move(storage_.value_);
mlamouri53f6b252016-04-19 17:27:01624 }
625
Daniel Cheng429dbdc52017-10-04 15:33:56626 constexpr const T&& value() const && {
jdoerriec85bfab2018-04-12 15:01:30627 CHECK(storage_.is_populated_);
kwiberg882859a2016-08-16 09:42:21628 return std::move(storage_.value_);
mlamouri53f6b252016-04-19 17:27:01629 }
630
631 template <class U>
632 constexpr T value_or(U&& default_value) const& {
633 // TODO(mlamouri): add the following assert when possible:
634 // static_assert(std::is_copy_constructible<T>::value,
635 // "T must be copy constructible");
636 static_assert(std::is_convertible<U, T>::value,
637 "U must be convertible to T");
Chris Blume0a5dd142018-01-24 22:35:40638 return storage_.is_populated_
639 ? value()
640 : static_cast<T>(std::forward<U>(default_value));
mlamouri53f6b252016-04-19 17:27:01641 }
642
643 template <class U>
Hidehiko Abeb467afe2018-02-23 07:01:30644 constexpr T value_or(U&& default_value) && {
mlamouri53f6b252016-04-19 17:27:01645 // TODO(mlamouri): add the following assert when possible:
646 // static_assert(std::is_move_constructible<T>::value,
647 // "T must be move constructible");
648 static_assert(std::is_convertible<U, T>::value,
649 "U must be convertible to T");
Chris Blume0a5dd142018-01-24 22:35:40650 return storage_.is_populated_
651 ? std::move(value())
652 : static_cast<T>(std::forward<U>(default_value));
mlamouri53f6b252016-04-19 17:27:01653 }
654
655 void swap(Optional& other) {
Chris Blume0a5dd142018-01-24 22:35:40656 if (!storage_.is_populated_ && !other.storage_.is_populated_)
mlamouri53f6b252016-04-19 17:27:01657 return;
658
Chris Blume0a5dd142018-01-24 22:35:40659 if (storage_.is_populated_ != other.storage_.is_populated_) {
660 if (storage_.is_populated_) {
Hidehiko Abe5134ab382018-01-08 09:38:16661 other.storage_.Init(std::move(storage_.value_));
mlamouri53f6b252016-04-19 17:27:01662 FreeIfNeeded();
Chris Blume0a5dd142018-01-24 22:35:40663 } else {
664 storage_.Init(std::move(other.storage_.value_));
665 other.FreeIfNeeded();
mlamouri53f6b252016-04-19 17:27:01666 }
667 return;
668 }
669
Chris Blume0a5dd142018-01-24 22:35:40670 DCHECK(storage_.is_populated_ && other.storage_.is_populated_);
mlamouri53f6b252016-04-19 17:27:01671 using std::swap;
672 swap(**this, *other);
673 }
674
Hidehiko Abe3aa61df2018-02-24 12:47:07675 void reset() { FreeIfNeeded(); }
mlamouri26204572016-08-10 12:24:15676
mlamouri53f6b252016-04-19 17:27:01677 template <class... Args>
Hidehiko Abeb467afe2018-02-23 07:01:30678 T& emplace(Args&&... args) {
mlamouri53f6b252016-04-19 17:27:01679 FreeIfNeeded();
Hidehiko Abe5134ab382018-01-08 09:38:16680 storage_.Init(std::forward<Args>(args)...);
Hidehiko Abeb467afe2018-02-23 07:01:30681 return storage_.value_;
mlamouri53f6b252016-04-19 17:27:01682 }
683
Hidehiko Abeb467afe2018-02-23 07:01:30684 template <class U, class... Args>
685 std::enable_if_t<
686 std::is_constructible<T, std::initializer_list<U>&, Args&&...>::value,
687 T&>
688 emplace(std::initializer_list<U> il, Args&&... args) {
jdoerrieb6e6c752018-01-03 09:13:45689 FreeIfNeeded();
Hidehiko Abe5134ab382018-01-08 09:38:16690 storage_.Init(il, std::forward<Args>(args)...);
jdoerrieb6e6c752018-01-03 09:13:45691 return storage_.value_;
692 }
693
mlamouri53f6b252016-04-19 17:27:01694 private:
Hidehiko Abe25bbd5e2017-12-20 04:43:07695 // Accessing template base class's protected member needs explicit
696 // declaration to do so.
Hidehiko Abe40ee4ae2018-02-23 04:24:12697 using internal::OptionalBase<T>::CopyAssign;
Hidehiko Abe25bbd5e2017-12-20 04:43:07698 using internal::OptionalBase<T>::FreeIfNeeded;
Hidehiko Abe25bbd5e2017-12-20 04:43:07699 using internal::OptionalBase<T>::InitOrAssign;
Hidehiko Abe40ee4ae2018-02-23 04:24:12700 using internal::OptionalBase<T>::MoveAssign;
Hidehiko Abe25bbd5e2017-12-20 04:43:07701 using internal::OptionalBase<T>::storage_;
mlamouri53f6b252016-04-19 17:27:01702};
703
Hidehiko Abe7a534c32017-12-20 10:56:26704// Here after defines comparation operators. The definition follows
705// http://en.cppreference.com/w/cpp/utility/optional/operator_cmp
706// while bool() casting is replaced by has_value() to meet the chromium
707// style guide.
708template <class T, class U>
709constexpr bool operator==(const Optional<T>& lhs, const Optional<U>& rhs) {
710 if (lhs.has_value() != rhs.has_value())
711 return false;
712 if (!lhs.has_value())
713 return true;
714 return *lhs == *rhs;
mlamouri53f6b252016-04-19 17:27:01715}
716
Hidehiko Abe7a534c32017-12-20 10:56:26717template <class T, class U>
718constexpr bool operator!=(const Optional<T>& lhs, const Optional<U>& rhs) {
719 if (lhs.has_value() != rhs.has_value())
720 return true;
721 if (!lhs.has_value())
722 return false;
723 return *lhs != *rhs;
mlamouri53f6b252016-04-19 17:27:01724}
725
Hidehiko Abe7a534c32017-12-20 10:56:26726template <class T, class U>
727constexpr bool operator<(const Optional<T>& lhs, const Optional<U>& rhs) {
728 if (!rhs.has_value())
729 return false;
730 if (!lhs.has_value())
731 return true;
732 return *lhs < *rhs;
mlamouri53f6b252016-04-19 17:27:01733}
734
Hidehiko Abe7a534c32017-12-20 10:56:26735template <class T, class U>
736constexpr bool operator<=(const Optional<T>& lhs, const Optional<U>& rhs) {
737 if (!lhs.has_value())
738 return true;
739 if (!rhs.has_value())
740 return false;
741 return *lhs <= *rhs;
mlamouri53f6b252016-04-19 17:27:01742}
743
Hidehiko Abe7a534c32017-12-20 10:56:26744template <class T, class U>
745constexpr bool operator>(const Optional<T>& lhs, const Optional<U>& rhs) {
746 if (!lhs.has_value())
747 return false;
748 if (!rhs.has_value())
749 return true;
750 return *lhs > *rhs;
mlamouri53f6b252016-04-19 17:27:01751}
752
Hidehiko Abe7a534c32017-12-20 10:56:26753template <class T, class U>
754constexpr bool operator>=(const Optional<T>& lhs, const Optional<U>& rhs) {
755 if (!rhs.has_value())
756 return true;
757 if (!lhs.has_value())
758 return false;
759 return *lhs >= *rhs;
mlamouri53f6b252016-04-19 17:27:01760}
761
762template <class T>
Hidehiko Abe25bbd5e2017-12-20 04:43:07763constexpr bool operator==(const Optional<T>& opt, nullopt_t) {
mlamouri53f6b252016-04-19 17:27:01764 return !opt;
765}
766
767template <class T>
Hidehiko Abe25bbd5e2017-12-20 04:43:07768constexpr bool operator==(nullopt_t, const Optional<T>& opt) {
mlamouri53f6b252016-04-19 17:27:01769 return !opt;
770}
771
772template <class T>
Hidehiko Abe25bbd5e2017-12-20 04:43:07773constexpr bool operator!=(const Optional<T>& opt, nullopt_t) {
Hidehiko Abe7a534c32017-12-20 10:56:26774 return opt.has_value();
mlamouri53f6b252016-04-19 17:27:01775}
776
777template <class T>
Hidehiko Abe25bbd5e2017-12-20 04:43:07778constexpr bool operator!=(nullopt_t, const Optional<T>& opt) {
Hidehiko Abe7a534c32017-12-20 10:56:26779 return opt.has_value();
mlamouri53f6b252016-04-19 17:27:01780}
781
782template <class T>
Hidehiko Abe25bbd5e2017-12-20 04:43:07783constexpr bool operator<(const Optional<T>& opt, nullopt_t) {
mlamouri53f6b252016-04-19 17:27:01784 return false;
785}
786
787template <class T>
Hidehiko Abe25bbd5e2017-12-20 04:43:07788constexpr bool operator<(nullopt_t, const Optional<T>& opt) {
Hidehiko Abe7a534c32017-12-20 10:56:26789 return opt.has_value();
mlamouri53f6b252016-04-19 17:27:01790}
791
792template <class T>
Hidehiko Abe25bbd5e2017-12-20 04:43:07793constexpr bool operator<=(const Optional<T>& opt, nullopt_t) {
mlamouri53f6b252016-04-19 17:27:01794 return !opt;
795}
796
797template <class T>
Hidehiko Abe25bbd5e2017-12-20 04:43:07798constexpr bool operator<=(nullopt_t, const Optional<T>& opt) {
mlamouri53f6b252016-04-19 17:27:01799 return true;
800}
801
802template <class T>
Hidehiko Abe25bbd5e2017-12-20 04:43:07803constexpr bool operator>(const Optional<T>& opt, nullopt_t) {
Hidehiko Abe7a534c32017-12-20 10:56:26804 return opt.has_value();
mlamouri53f6b252016-04-19 17:27:01805}
806
807template <class T>
Hidehiko Abe25bbd5e2017-12-20 04:43:07808constexpr bool operator>(nullopt_t, const Optional<T>& opt) {
mlamouri53f6b252016-04-19 17:27:01809 return false;
810}
811
812template <class T>
Hidehiko Abe25bbd5e2017-12-20 04:43:07813constexpr bool operator>=(const Optional<T>& opt, nullopt_t) {
mlamouri53f6b252016-04-19 17:27:01814 return true;
815}
816
817template <class T>
Hidehiko Abe25bbd5e2017-12-20 04:43:07818constexpr bool operator>=(nullopt_t, const Optional<T>& opt) {
mlamouri53f6b252016-04-19 17:27:01819 return !opt;
820}
821
Hidehiko Abe7a534c32017-12-20 10:56:26822template <class T, class U>
823constexpr bool operator==(const Optional<T>& opt, const U& value) {
824 return opt.has_value() ? *opt == value : false;
mlamouri53f6b252016-04-19 17:27:01825}
826
Hidehiko Abe7a534c32017-12-20 10:56:26827template <class T, class U>
828constexpr bool operator==(const U& value, const Optional<T>& opt) {
829 return opt.has_value() ? value == *opt : false;
mlamouri53f6b252016-04-19 17:27:01830}
831
Hidehiko Abe7a534c32017-12-20 10:56:26832template <class T, class U>
833constexpr bool operator!=(const Optional<T>& opt, const U& value) {
834 return opt.has_value() ? *opt != value : true;
mlamouri53f6b252016-04-19 17:27:01835}
836
Hidehiko Abe7a534c32017-12-20 10:56:26837template <class T, class U>
838constexpr bool operator!=(const U& value, const Optional<T>& opt) {
839 return opt.has_value() ? value != *opt : true;
mlamouri53f6b252016-04-19 17:27:01840}
841
Hidehiko Abe7a534c32017-12-20 10:56:26842template <class T, class U>
843constexpr bool operator<(const Optional<T>& opt, const U& value) {
844 return opt.has_value() ? *opt < value : true;
mlamouri53f6b252016-04-19 17:27:01845}
846
Hidehiko Abe7a534c32017-12-20 10:56:26847template <class T, class U>
848constexpr bool operator<(const U& value, const Optional<T>& opt) {
849 return opt.has_value() ? value < *opt : false;
mlamouri53f6b252016-04-19 17:27:01850}
851
Hidehiko Abe7a534c32017-12-20 10:56:26852template <class T, class U>
853constexpr bool operator<=(const Optional<T>& opt, const U& value) {
854 return opt.has_value() ? *opt <= value : true;
mlamouri53f6b252016-04-19 17:27:01855}
856
Hidehiko Abe7a534c32017-12-20 10:56:26857template <class T, class U>
858constexpr bool operator<=(const U& value, const Optional<T>& opt) {
859 return opt.has_value() ? value <= *opt : false;
mlamouri53f6b252016-04-19 17:27:01860}
861
Hidehiko Abe7a534c32017-12-20 10:56:26862template <class T, class U>
863constexpr bool operator>(const Optional<T>& opt, const U& value) {
864 return opt.has_value() ? *opt > value : false;
mlamouri53f6b252016-04-19 17:27:01865}
866
Hidehiko Abe7a534c32017-12-20 10:56:26867template <class T, class U>
868constexpr bool operator>(const U& value, const Optional<T>& opt) {
869 return opt.has_value() ? value > *opt : true;
mlamouri53f6b252016-04-19 17:27:01870}
871
Hidehiko Abe7a534c32017-12-20 10:56:26872template <class T, class U>
873constexpr bool operator>=(const Optional<T>& opt, const U& value) {
874 return opt.has_value() ? *opt >= value : false;
mlamouri53f6b252016-04-19 17:27:01875}
876
Hidehiko Abe7a534c32017-12-20 10:56:26877template <class T, class U>
878constexpr bool operator>=(const U& value, const Optional<T>& opt) {
879 return opt.has_value() ? value >= *opt : true;
mlamouri53f6b252016-04-19 17:27:01880}
881
882template <class T>
Hidehiko Abeb467afe2018-02-23 07:01:30883constexpr Optional<std::decay_t<T>> make_optional(T&& value) {
884 return Optional<std::decay_t<T>>(std::forward<T>(value));
885}
886
887template <class T, class... Args>
888constexpr Optional<T> make_optional(Args&&... args) {
889 return Optional<T>(in_place, std::forward<Args>(args)...);
mlamouri53f6b252016-04-19 17:27:01890}
891
jdoerrieb6e6c752018-01-03 09:13:45892template <class T, class U, class... Args>
893constexpr Optional<T> make_optional(std::initializer_list<U> il,
894 Args&&... args) {
895 return Optional<T>(in_place, il, std::forward<Args>(args)...);
896}
897
Hidehiko Abeb467afe2018-02-23 07:01:30898// Partial specialization for a function template is not allowed. Also, it is
899// not allowed to add overload function to std namespace, while it is allowed
900// to specialize the template in std. Thus, swap() (kind of) overloading is
901// defined in base namespace, instead.
mlamouri53f6b252016-04-19 17:27:01902template <class T>
Hidehiko Abeb467afe2018-02-23 07:01:30903std::enable_if_t<std::is_move_constructible<T>::value &&
904 internal::IsSwappable<T>::value>
905swap(Optional<T>& lhs, Optional<T>& rhs) {
mlamouri53f6b252016-04-19 17:27:01906 lhs.swap(rhs);
907}
908
909} // namespace base
910
911namespace std {
912
913template <class T>
914struct hash<base::Optional<T>> {
915 size_t operator()(const base::Optional<T>& opt) const {
916 return opt == base::nullopt ? 0 : std::hash<T>()(*opt);
917 }
918};
919
920} // namespace std
921
922#endif // BASE_OPTIONAL_H_