optional.h 33 KB

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