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.
19 #include <type_traits>
23 namespace folly { namespace wangle {
27 static_assert(!std::is_reference<T>::value,
28 "Try may not be used with reference types");
37 typedef T element_type;
39 Try() : contains_(Contains::NOTHING) {}
40 explicit Try(const T& v) : contains_(Contains::VALUE), value_(v) {}
41 explicit Try(T&& v) : contains_(Contains::VALUE), value_(std::move(v)) {}
42 explicit Try(std::exception_ptr e) : contains_(Contains::EXCEPTION), e_(e) {}
46 Try& operator=(Try<T>&& t);
49 Try(const Try<T>& t) = delete;
50 Try& operator=(const Try<T>& t) = delete;
55 const T& value() const;
57 void throwIfFailed() const;
59 const T& operator*() const { return value(); }
60 T& operator*() { return value(); }
62 const T* operator->() const { return &value(); }
63 T* operator->() { return &value(); }
65 bool hasValue() const { return contains_ == Contains::VALUE; }
66 bool hasException() const { return contains_ == Contains::EXCEPTION; }
72 std::exception_ptr e_;
79 Try() : hasValue_(true) {}
80 explicit Try(std::exception_ptr e) : hasValue_(false), e_(e) {}
82 void value() const { throwIfFailed(); }
83 void operator*() const { return value(); }
85 inline void throwIfFailed() const;
87 bool hasValue() const { return hasValue_; }
88 bool hasException() const { return !hasValue_; }
92 std::exception_ptr e_;
96 * Extracts value from try and returns it. Throws if try contained an exception.
99 T moveFromTry(wangle::Try<T>&& t);
102 * Throws if try contained an exception.
104 void moveFromTry(wangle::Try<void>&& t);
107 * Constructs Try based on the result of execution of function f (e.g. result
110 template <typename F>
111 typename std::enable_if<
112 !std::is_same<typename std::result_of<F()>::type, void>::value,
113 Try<typename std::result_of<F()>::type>>::type
114 makeTryFunction(F&& f);
117 * makeTryFunction specialization for void functions.
119 template <typename F>
120 typename std::enable_if<
121 std::is_same<typename std::result_of<F()>::type, void>::value,
123 makeTryFunction(F&& f);
128 #include <folly/wangle/Try-inl.h>