2 * Copyright 2014 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"
88 static_assert(!std::is_reference<Value>::value,
89 "Optional may not be used with reference types");
95 Optional(const Optional& src)
96 noexcept(std::is_nothrow_copy_constructible<Value>::value) {
99 construct(src.value());
105 Optional(Optional&& src)
106 noexcept(std::is_nothrow_move_constructible<Value>::value) {
108 if (src.hasValue()) {
109 construct(std::move(src.value()));
116 /* 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 ~Optional() noexcept {
134 void assign(const None&) {
138 void assign(Optional&& src) {
140 if (src.hasValue()) {
141 assign(std::move(src.value()));
149 void assign(const Optional& src) {
150 if (src.hasValue()) {
157 void assign(Value&& newValue) {
159 value_ = std::move(newValue);
161 construct(std::move(newValue));
165 void assign(const Value& newValue) {
174 Optional& operator=(Arg&& arg) {
175 assign(std::forward<Arg>(arg));
179 Optional& operator=(Optional &&other)
180 noexcept (std::is_nothrow_move_assignable<Value>::value) {
182 assign(std::move(other));
186 Optional& operator=(const Optional &other)
187 noexcept (std::is_nothrow_copy_assignable<Value>::value) {
193 template<class... Args>
194 void emplace(Args&&... args) {
196 construct(std::forward<Args>(args)...);
206 const Value& value() const {
216 bool hasValue() const { return hasValue_; }
218 explicit operator bool() const {
222 const Value& operator*() const { return value(); }
223 Value& operator*() { return value(); }
225 const Value* operator->() const { return &value(); }
226 Value* operator->() { return &value(); }
228 // Return a copy of the value if set, or a given default if not.
230 Value value_or(U&& dflt) const& {
231 return hasValue_ ? value_ : std::forward<U>(dflt);
235 Value value_or(U&& dflt) && {
236 return hasValue_ ? std::move(value_) : std::forward<U>(dflt);
240 template<class... Args>
241 void construct(Args&&... args) {
242 const void* ptr = &value_;
243 // for supporting const types
244 new(const_cast<void*>(ptr)) Value(std::forward<Args>(args)...);
249 union { Value value_; };
253 #if defined(__GNUC__) && !defined(__clang__)
254 #pragma GCC diagnostic pop
258 const T* get_pointer(const Optional<T>& opt) {
259 return opt ? &opt.value() : nullptr;
263 T* get_pointer(Optional<T>& opt) {
264 return opt ? &opt.value() : nullptr;
268 void swap(Optional<T>& a, Optional<T>& b) {
269 if (a.hasValue() && b.hasValue()) {
272 swap(a.value(), b.value());
273 } else if (a.hasValue() || b.hasValue()) {
274 std::swap(a, b); // fall back to default implementation if they're mixed.
279 class Opt = Optional<typename std::decay<T>::type>>
280 Opt make_optional(T&& v) {
281 return Opt(std::forward<T>(v));
284 ///////////////////////////////////////////////////////////////////////////////
288 bool operator==(const Optional<V>& a, const V& b) {
289 return a.hasValue() && a.value() == b;
293 bool operator!=(const Optional<V>& a, const V& b) {
298 bool operator==(const V& a, const Optional<V>& b) {
299 return b.hasValue() && b.value() == a;
303 bool operator!=(const V& a, const Optional<V>& b) {
308 bool operator==(const Optional<V>& a, const Optional<V>& b) {
309 if (a.hasValue() != b.hasValue()) { return false; }
310 if (a.hasValue()) { return a.value() == b.value(); }
315 bool operator!=(const Optional<V>& a, const Optional<V>& b) {
320 bool operator< (const Optional<V>& a, const Optional<V>& b) {
321 if (a.hasValue() != b.hasValue()) { return a.hasValue() < b.hasValue(); }
322 if (a.hasValue()) { return a.value() < b.value(); }
327 bool operator> (const Optional<V>& a, const Optional<V>& b) {
332 bool operator<=(const Optional<V>& a, const Optional<V>& b) {
337 bool operator>=(const Optional<V>& a, const Optional<V>& b) {
341 // Suppress comparability of Optional<T> with T, despite implicit conversion.
342 template<class V> bool operator< (const Optional<V>&, const V& other) = delete;
343 template<class V> bool operator<=(const Optional<V>&, const V& other) = delete;
344 template<class V> bool operator>=(const Optional<V>&, const V& other) = delete;
345 template<class V> bool operator> (const Optional<V>&, const V& other) = delete;
346 template<class V> bool operator< (const V& other, const Optional<V>&) = delete;
347 template<class V> bool operator<=(const V& other, const Optional<V>&) = delete;
348 template<class V> bool operator>=(const V& other, const Optional<V>&) = delete;
349 template<class V> bool operator> (const V& other, const Optional<V>&) = delete;
351 ///////////////////////////////////////////////////////////////////////////////
355 #endif // FOLLY_OPTIONAL_H_