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;
70 class OptionalEmptyException : public std::runtime_error {
72 OptionalEmptyException()
73 : std::runtime_error("Empty Optional cannot be unwrapped") {}
79 typedef Value value_type;
81 static_assert(!std::is_reference<Value>::value,
82 "Optional may not be used with reference types");
83 static_assert(!std::is_abstract<Value>::value,
84 "Optional may not be used with abstract types");
89 Optional(const Optional& src)
90 noexcept(std::is_nothrow_copy_constructible<Value>::value) {
93 construct(src.value());
97 Optional(Optional&& src)
98 noexcept(std::is_nothrow_move_constructible<Value>::value) {
100 if (src.hasValue()) {
101 construct(std::move(src.value()));
106 /* implicit */ Optional(const None&) noexcept {
109 /* implicit */ Optional(Value&& newValue)
110 noexcept(std::is_nothrow_move_constructible<Value>::value) {
111 construct(std::move(newValue));
114 /* implicit */ Optional(const Value& newValue)
115 noexcept(std::is_nothrow_copy_constructible<Value>::value) {
119 void assign(const None&) {
123 void assign(Optional&& src) {
125 if (src.hasValue()) {
126 assign(std::move(src.value()));
134 void assign(const Optional& src) {
135 if (src.hasValue()) {
142 void assign(Value&& newValue) {
144 storage_.value = std::move(newValue);
146 construct(std::move(newValue));
150 void assign(const Value& newValue) {
152 storage_.value = newValue;
159 Optional& operator=(Arg&& arg) {
160 assign(std::forward<Arg>(arg));
164 Optional& operator=(Optional &&other)
165 noexcept (std::is_nothrow_move_assignable<Value>::value) {
167 assign(std::move(other));
171 Optional& operator=(const Optional &other)
172 noexcept (std::is_nothrow_copy_assignable<Value>::value) {
178 template<class... Args>
179 void emplace(Args&&... args) {
181 construct(std::forward<Args>(args)...);
188 const Value& value() const& {
190 return storage_.value;
195 return storage_.value;
200 return std::move(storage_.value);
203 const Value&& value() const&& {
205 return std::move(storage_.value);
208 const Value* get_pointer() const& {
209 return storage_.hasValue ? &storage_.value : nullptr;
211 Value* get_pointer() & {
212 return storage_.hasValue ? &storage_.value : nullptr;
214 Value* get_pointer() && = delete;
216 bool hasValue() const { return storage_.hasValue; }
218 explicit operator bool() const {
222 const Value& operator*() const& { return value(); }
223 Value& operator*() & { return value(); }
224 const Value&& operator*() const&& { return std::move(value()); }
225 Value&& operator*() && { return std::move(value()); }
227 const Value* operator->() const { return &value(); }
228 Value* operator->() { return &value(); }
230 // Return a copy of the value if set, or a given default if not.
232 Value value_or(U&& dflt) const& {
233 if (storage_.hasValue) {
234 return storage_.value;
237 return std::forward<U>(dflt);
241 Value value_or(U&& dflt) && {
242 if (storage_.hasValue) {
243 return std::move(storage_.value);
246 return std::forward<U>(dflt);
250 void require_value() const {
251 if (!storage_.hasValue) {
252 throw OptionalEmptyException();
256 template<class... Args>
257 void construct(Args&&... args) {
258 const void* ptr = &storage_.value;
259 // for supporting const types
260 new(const_cast<void*>(ptr)) Value(std::forward<Args>(args)...);
261 storage_.hasValue = true;
264 struct StorageTriviallyDestructible {
265 // The union trick allows to initialize the Optional's memory,
266 // so that compiler/tools don't complain about unitialized memory,
267 // without actually calling Value's default constructor.
268 // The rest of the implementation enforces that hasValue/value are
273 bool paddingForHasValue_[1];
278 StorageTriviallyDestructible() : hasValue{false} {}
285 struct StorageNonTriviallyDestructible {
286 // See StorageTriviallyDestructible's union
290 bool paddingForHasValue_[1];
295 StorageNonTriviallyDestructible() : hasValue{false} {}
296 ~StorageNonTriviallyDestructible() {
309 typename std::conditional<std::is_trivially_destructible<Value>::value,
310 StorageTriviallyDestructible,
311 StorageNonTriviallyDestructible>::type;
317 const T* get_pointer(const Optional<T>& opt) {
318 return opt.get_pointer();
322 T* get_pointer(Optional<T>& opt) {
323 return opt.get_pointer();
327 void swap(Optional<T>& a, Optional<T>& b) {
328 if (a.hasValue() && b.hasValue()) {
331 swap(a.value(), b.value());
332 } else if (a.hasValue() || b.hasValue()) {
333 std::swap(a, b); // fall back to default implementation if they're mixed.
338 class Opt = Optional<typename std::decay<T>::type>>
339 Opt make_optional(T&& v) {
340 return Opt(std::forward<T>(v));
343 ///////////////////////////////////////////////////////////////////////////////
347 bool operator==(const Optional<V>& a, const V& b) {
348 return a.hasValue() && a.value() == b;
352 bool operator!=(const Optional<V>& a, const V& b) {
357 bool operator==(const V& a, const Optional<V>& b) {
358 return b.hasValue() && b.value() == a;
362 bool operator!=(const V& a, const Optional<V>& b) {
367 bool operator==(const Optional<V>& a, const Optional<V>& b) {
368 if (a.hasValue() != b.hasValue()) { return false; }
369 if (a.hasValue()) { return a.value() == b.value(); }
374 bool operator!=(const Optional<V>& a, const Optional<V>& b) {
379 bool operator< (const Optional<V>& a, const Optional<V>& b) {
380 if (a.hasValue() != b.hasValue()) { return a.hasValue() < b.hasValue(); }
381 if (a.hasValue()) { return a.value() < b.value(); }
386 bool operator> (const Optional<V>& a, const Optional<V>& b) {
391 bool operator<=(const Optional<V>& a, const Optional<V>& b) {
396 bool operator>=(const Optional<V>& a, const Optional<V>& b) {
400 // Suppress comparability of Optional<T> with T, despite implicit conversion.
401 template<class V> bool operator< (const Optional<V>&, const V& other) = delete;
402 template<class V> bool operator<=(const Optional<V>&, const V& other) = delete;
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 V& other, const Optional<V>&) = delete;
406 template<class V> bool operator<=(const V& other, const Optional<V>&) = 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;
410 ///////////////////////////////////////////////////////////////////////////////