2 * Copyright 2015 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.
17 #ifndef FOLLY_OPTIONAL_H_
18 #define FOLLY_OPTIONAL_H_
21 * Optional - For conditional initialization of values, like boost::optional,
22 * but with support for move semantics and emplacement. Reference type support
23 * has not been included due to limited use cases and potential confusion with
24 * semantics of assignment: Assigning to an optional reference could quite
25 * reasonably copy its value or redirect the reference.
27 * Optional can be useful when a variable might or might not be needed:
29 * Optional<Logger> maybeLogger = ...;
31 * maybeLogger->log("hello");
34 * Optional enables a 'null' value for types which do not otherwise have
35 * nullability, especially useful for parameter passing:
37 * void testIterator(const unique_ptr<Iterator>& it,
38 * initializer_list<int> idsExpected,
39 * Optional<initializer_list<int>> ranksExpected = none) {
40 * for (int i = 0; it->next(); ++i) {
41 * EXPECT_EQ(it->doc().id(), idsExpected[i]);
42 * if (ranksExpected) {
43 * EXPECT_EQ(it->doc().rank(), (*ranksExpected)[i]);
48 * Optional models OptionalPointee, so calling 'get_pointer(opt)' will return a
49 * pointer to nullptr if the 'opt' is empty, and a pointer to the value if it is
52 * Optional<int> maybeInt = ...;
53 * if (int* v = get_pointer(maybeInt)) {
59 #include <type_traits>
62 #include <boost/operators.hpp>
64 #include <folly/Portability.h>
68 namespace detail { struct NoneHelper {}; }
70 typedef int detail::NoneHelper::*None;
72 const None none = nullptr;
75 * gcc-4.7 warns about use of uninitialized memory around the use of storage_
76 * even though this is explicitly initialized at each point.
78 #if defined(__GNUC__) && !defined(__clang__)
79 # pragma GCC diagnostic push
80 # pragma GCC diagnostic ignored "-Wuninitialized"
81 # pragma GCC diagnostic ignored "-Wpragmas"
82 # pragma GCC diagnostic ignored "-Wmaybe-uninitialized"
85 class OptionalEmptyException : public std::runtime_error {
87 OptionalEmptyException()
88 : std::runtime_error("Empty Optional cannot be unwrapped") {}
94 static_assert(!std::is_reference<Value>::value,
95 "Optional may not be used with reference types");
96 static_assert(!std::is_abstract<Value>::value,
97 "Optional may not be used with abstract types");
103 Optional(const Optional& src)
104 noexcept(std::is_nothrow_copy_constructible<Value>::value) {
106 if (src.hasValue()) {
107 construct(src.value());
113 Optional(Optional&& src)
114 noexcept(std::is_nothrow_move_constructible<Value>::value) {
116 if (src.hasValue()) {
117 construct(std::move(src.value()));
124 /* implicit */ Optional(const None&) noexcept
128 /* implicit */ Optional(Value&& newValue)
129 noexcept(std::is_nothrow_move_constructible<Value>::value) {
130 construct(std::move(newValue));
133 /* implicit */ Optional(const Value& newValue)
134 noexcept(std::is_nothrow_copy_constructible<Value>::value) {
138 ~Optional() noexcept {
142 void assign(const None&) {
146 void assign(Optional&& src) {
148 if (src.hasValue()) {
149 assign(std::move(src.value()));
157 void assign(const Optional& src) {
158 if (src.hasValue()) {
165 void assign(Value&& newValue) {
167 value_ = std::move(newValue);
169 construct(std::move(newValue));
173 void assign(const Value& newValue) {
182 Optional& operator=(Arg&& arg) {
183 assign(std::forward<Arg>(arg));
187 Optional& operator=(Optional &&other)
188 noexcept (std::is_nothrow_move_assignable<Value>::value) {
190 assign(std::move(other));
194 Optional& operator=(const Optional &other)
195 noexcept (std::is_nothrow_copy_assignable<Value>::value) {
201 template<class... Args>
202 void emplace(Args&&... args) {
204 construct(std::forward<Args>(args)...);
214 const Value& value() const& {
226 return std::move(value_);
229 const Value* get_pointer() const& { return hasValue_ ? &value_ : nullptr; }
230 Value* get_pointer() & { return hasValue_ ? &value_ : nullptr; }
231 Value* get_pointer() && = delete;
233 bool hasValue() const { return hasValue_; }
235 explicit operator bool() const {
239 const Value& operator*() const& { return value(); }
240 Value& operator*() & { return value(); }
241 Value operator*() && { return std::move(value()); }
243 const Value* operator->() const { return &value(); }
244 Value* operator->() { return &value(); }
246 // Return a copy of the value if set, or a given default if not.
248 Value value_or(U&& dflt) const& {
249 return hasValue_ ? value_ : std::forward<U>(dflt);
253 Value value_or(U&& dflt) && {
254 return hasValue_ ? std::move(value_) : std::forward<U>(dflt);
258 void require_value() const {
260 throw OptionalEmptyException();
264 template<class... Args>
265 void construct(Args&&... args) {
266 const void* ptr = &value_;
267 // for supporting const types
268 new(const_cast<void*>(ptr)) Value(std::forward<Args>(args)...);
273 union { Value value_; };
277 #if defined(__GNUC__) && !defined(__clang__)
278 #pragma GCC diagnostic pop
282 const T* get_pointer(const Optional<T>& opt) {
283 return opt.get_pointer();
287 T* get_pointer(Optional<T>& opt) {
288 return opt.get_pointer();
292 void swap(Optional<T>& a, Optional<T>& b) {
293 if (a.hasValue() && b.hasValue()) {
296 swap(a.value(), b.value());
297 } else if (a.hasValue() || b.hasValue()) {
298 std::swap(a, b); // fall back to default implementation if they're mixed.
303 class Opt = Optional<typename std::decay<T>::type>>
304 Opt make_optional(T&& v) {
305 return Opt(std::forward<T>(v));
308 ///////////////////////////////////////////////////////////////////////////////
312 bool operator==(const Optional<V>& a, const V& b) {
313 return a.hasValue() && a.value() == b;
317 bool operator!=(const Optional<V>& a, const V& b) {
322 bool operator==(const V& a, const Optional<V>& b) {
323 return b.hasValue() && b.value() == a;
327 bool operator!=(const V& a, const Optional<V>& b) {
332 bool operator==(const Optional<V>& a, const Optional<V>& b) {
333 if (a.hasValue() != b.hasValue()) { return false; }
334 if (a.hasValue()) { return a.value() == b.value(); }
339 bool operator!=(const Optional<V>& a, const Optional<V>& b) {
344 bool operator< (const Optional<V>& a, const Optional<V>& b) {
345 if (a.hasValue() != b.hasValue()) { return a.hasValue() < b.hasValue(); }
346 if (a.hasValue()) { return a.value() < b.value(); }
351 bool operator> (const Optional<V>& a, const Optional<V>& b) {
356 bool operator<=(const Optional<V>& a, const Optional<V>& b) {
361 bool operator>=(const Optional<V>& a, const Optional<V>& b) {
365 // Suppress comparability of Optional<T> with T, despite implicit conversion.
366 template<class V> bool operator< (const Optional<V>&, const V& other) = delete;
367 template<class V> bool operator<=(const Optional<V>&, const V& other) = delete;
368 template<class V> bool operator>=(const Optional<V>&, const V& other) = delete;
369 template<class V> bool operator> (const Optional<V>&, const V& other) = delete;
370 template<class V> bool operator< (const V& other, const Optional<V>&) = delete;
371 template<class V> bool operator<=(const V& other, const Optional<V>&) = delete;
372 template<class V> bool operator>=(const V& other, const Optional<V>&) = delete;
373 template<class V> bool operator> (const V& other, const Optional<V>&) = delete;
375 ///////////////////////////////////////////////////////////////////////////////
379 #endif // FOLLY_OPTIONAL_H_