2 * Copyright 2016 Facebook, Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
20 * Optional - For conditional initialization of values, like boost::optional,
21 * but with support for move semantics and emplacement. Reference type support
22 * has not been included due to limited use cases and potential confusion with
23 * semantics of assignment: Assigning to an optional reference could quite
24 * reasonably copy its value or redirect the reference.
26 * Optional can be useful when a variable might or might not be needed:
28 * Optional<Logger> maybeLogger = ...;
30 * maybeLogger->log("hello");
33 * Optional enables a 'null' value for types which do not otherwise have
34 * nullability, especially useful for parameter passing:
36 * void testIterator(const unique_ptr<Iterator>& it,
37 * initializer_list<int> idsExpected,
38 * Optional<initializer_list<int>> ranksExpected = none) {
39 * for (int i = 0; it->next(); ++i) {
40 * EXPECT_EQ(it->doc().id(), idsExpected[i]);
41 * if (ranksExpected) {
42 * EXPECT_EQ(it->doc().rank(), (*ranksExpected)[i]);
47 * Optional models OptionalPointee, so calling 'get_pointer(opt)' will return a
48 * pointer to nullptr if the 'opt' is empty, and a pointer to the value if it is
51 * Optional<int> maybeInt = ...;
52 * if (int* v = get_pointer(maybeInt)) {
59 #include <type_traits>
64 namespace detail { struct NoneHelper {}; }
66 typedef int detail::NoneHelper::*None;
68 const None none = nullptr;
71 * gcc-4.7 warns about use of uninitialized memory around the use of storage_
72 * even though this is explicitly initialized at each point.
74 #if defined(__GNUC__) && !defined(__clang__)
75 # pragma GCC diagnostic push
76 # pragma GCC diagnostic ignored "-Wuninitialized"
77 # pragma GCC diagnostic ignored "-Wpragmas"
78 # pragma GCC diagnostic ignored "-Wmaybe-uninitialized"
81 class OptionalEmptyException : public std::runtime_error {
83 OptionalEmptyException()
84 : std::runtime_error("Empty Optional cannot be unwrapped") {}
90 typedef Value value_type;
92 static_assert(!std::is_reference<Value>::value,
93 "Optional may not be used with reference types");
94 static_assert(!std::is_abstract<Value>::value,
95 "Optional may not be used with abstract types");
100 Optional(const Optional& src)
101 noexcept(std::is_nothrow_copy_constructible<Value>::value) {
103 if (src.hasValue()) {
104 construct(src.value());
108 Optional(Optional&& src)
109 noexcept(std::is_nothrow_move_constructible<Value>::value) {
111 if (src.hasValue()) {
112 construct(std::move(src.value()));
117 /* implicit */ Optional(const None&) noexcept {
120 /* implicit */ Optional(Value&& newValue)
121 noexcept(std::is_nothrow_move_constructible<Value>::value) {
122 construct(std::move(newValue));
125 /* implicit */ Optional(const Value& newValue)
126 noexcept(std::is_nothrow_copy_constructible<Value>::value) {
130 void assign(const None&) {
134 void assign(Optional&& src) {
136 if (src.hasValue()) {
137 assign(std::move(src.value()));
145 void assign(const Optional& src) {
146 if (src.hasValue()) {
153 void assign(Value&& newValue) {
155 storage_.value = std::move(newValue);
157 construct(std::move(newValue));
161 void assign(const Value& newValue) {
163 storage_.value = newValue;
170 Optional& operator=(Arg&& arg) {
171 assign(std::forward<Arg>(arg));
175 Optional& operator=(Optional &&other)
176 noexcept (std::is_nothrow_move_assignable<Value>::value) {
178 assign(std::move(other));
182 Optional& operator=(const Optional &other)
183 noexcept (std::is_nothrow_copy_assignable<Value>::value) {
189 template<class... Args>
190 void emplace(Args&&... args) {
192 construct(std::forward<Args>(args)...);
199 const Value& value() const& {
201 return storage_.value;
206 return storage_.value;
209 // TODO: This should return Value&& instead of Value. Like with
210 // std::move, the calling code should decide whether it wants the move
211 // to happen or not. See std::optional.
214 return std::move(storage_.value);
217 const Value* get_pointer() const& {
218 return storage_.hasValue ? &storage_.value : nullptr;
220 Value* get_pointer() & {
221 return storage_.hasValue ? &storage_.value : nullptr;
223 Value* get_pointer() && = delete;
225 bool hasValue() const { return storage_.hasValue; }
227 explicit operator bool() const {
231 const Value& operator*() const& { return value(); }
232 Value& operator*() & { return value(); }
233 // TODO: This should return Value&& instead of Value. Like with
234 // std::move, the calling code should decide whether it wants the move
235 // to happen or not. See std::optional.
236 Value operator*() && { return std::move(value()); }
238 const Value* operator->() const { return &value(); }
239 Value* operator->() { return &value(); }
241 // Return a copy of the value if set, or a given default if not.
243 Value value_or(U&& dflt) const& {
244 if (storage_.hasValue) {
245 return storage_.value;
248 return std::forward<U>(dflt);
252 Value value_or(U&& dflt) && {
253 if (storage_.hasValue) {
254 return std::move(storage_.value);
257 return std::forward<U>(dflt);
261 void require_value() const {
262 if (!storage_.hasValue) {
263 throw OptionalEmptyException();
267 template<class... Args>
268 void construct(Args&&... args) {
269 const void* ptr = &storage_.value;
270 // for supporting const types
271 new(const_cast<void*>(ptr)) Value(std::forward<Args>(args)...);
272 storage_.hasValue = true;
275 struct StorageTriviallyDestructible {
277 union { Value value; };
280 StorageTriviallyDestructible() : hasValue{false} {}
287 struct StorageNonTriviallyDestructible {
289 union { Value value; };
292 StorageNonTriviallyDestructible() : hasValue{false} {}
294 ~StorageNonTriviallyDestructible() {
307 typename std::conditional<std::is_trivially_destructible<Value>::value,
308 StorageTriviallyDestructible,
309 StorageNonTriviallyDestructible>::type;
314 #if defined(__GNUC__) && !defined(__clang__)
315 #pragma GCC diagnostic pop
319 const T* get_pointer(const Optional<T>& opt) {
320 return opt.get_pointer();
324 T* get_pointer(Optional<T>& opt) {
325 return opt.get_pointer();
329 void swap(Optional<T>& a, Optional<T>& b) {
330 if (a.hasValue() && b.hasValue()) {
333 swap(a.value(), b.value());
334 } else if (a.hasValue() || b.hasValue()) {
335 std::swap(a, b); // fall back to default implementation if they're mixed.
340 class Opt = Optional<typename std::decay<T>::type>>
341 Opt make_optional(T&& v) {
342 return Opt(std::forward<T>(v));
345 ///////////////////////////////////////////////////////////////////////////////
349 bool operator==(const Optional<V>& a, const V& b) {
350 return a.hasValue() && a.value() == b;
354 bool operator!=(const Optional<V>& a, const V& b) {
359 bool operator==(const V& a, const Optional<V>& b) {
360 return b.hasValue() && b.value() == a;
364 bool operator!=(const V& a, const Optional<V>& b) {
369 bool operator==(const Optional<V>& a, const Optional<V>& b) {
370 if (a.hasValue() != b.hasValue()) { return false; }
371 if (a.hasValue()) { return a.value() == b.value(); }
376 bool operator!=(const Optional<V>& a, const Optional<V>& b) {
381 bool operator< (const Optional<V>& a, const Optional<V>& b) {
382 if (a.hasValue() != b.hasValue()) { return a.hasValue() < b.hasValue(); }
383 if (a.hasValue()) { return a.value() < b.value(); }
388 bool operator> (const Optional<V>& a, const Optional<V>& b) {
393 bool operator<=(const Optional<V>& a, const Optional<V>& b) {
398 bool operator>=(const Optional<V>& a, const Optional<V>& b) {
402 // Suppress comparability of Optional<T> with T, despite implicit conversion.
403 template<class V> bool operator< (const Optional<V>&, const V& other) = delete;
404 template<class V> bool operator<=(const Optional<V>&, const V& other) = delete;
405 template<class V> bool operator>=(const Optional<V>&, const V& other) = delete;
406 template<class V> bool operator> (const Optional<V>&, const V& other) = delete;
407 template<class V> bool operator< (const V& other, const Optional<V>&) = delete;
408 template<class V> bool operator<=(const V& other, const Optional<V>&) = delete;
409 template<class V> bool operator>=(const V& other, const Optional<V>&) = delete;
410 template<class V> bool operator> (const V& other, const Optional<V>&) = delete;
412 ///////////////////////////////////////////////////////////////////////////////