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 namespace folly { namespace wangle {
23 static_assert(!std::is_reference<T>::value,
24 "Try may not be used with reference types");
33 typedef T element_type;
35 Try() : contains_(Contains::NOTHING) {}
36 explicit Try(const T& v) : contains_(Contains::VALUE), value_(v) {}
37 explicit Try(T&& v) : contains_(Contains::VALUE), value_(std::move(v)) {}
38 explicit Try(std::exception_ptr e) : contains_(Contains::EXCEPTION), e_(e) {}
42 Try& operator=(Try<T>&& t);
45 Try(const Try<T>& t) = delete;
46 Try& operator=(const Try<T>& t) = delete;
51 const T& value() const;
53 void throwIfFailed() const;
55 const T& operator*() const { return value(); }
56 T& operator*() { return value(); }
58 const T* operator->() const { return &value(); }
59 T* operator->() { return &value(); }
61 bool hasValue() const { return contains_ == Contains::VALUE; }
62 bool hasException() const { return contains_ == Contains::EXCEPTION; }
68 std::exception_ptr e_;
75 Try() : hasValue_(true) {}
76 explicit Try(std::exception_ptr e) : hasValue_(false), e_(e) {}
78 void value() const { throwIfFailed(); }
79 void operator*() const { return value(); }
81 inline void throwIfFailed() const;
83 bool hasValue() const { return hasValue_; }
84 bool hasException() const { return !hasValue_; }
88 std::exception_ptr e_;
92 * Extracts value from try and returns it. Throws if try contained an exception.
95 T moveFromTry(wangle::Try<T>&& t);
98 * Throws if try contained an exception.
100 void moveFromTry(wangle::Try<void>&& t);
103 * Constructs Try based on the result of execution of function f (e.g. result
106 template <typename F>
107 typename std::enable_if<
108 !std::is_same<typename std::result_of<F()>::type, void>::value,
109 Try<typename std::result_of<F()>::type>>::type
110 makeTryFunction(F&& f);
113 * makeTryFunction specialization for void functions.
115 template <typename F>
116 typename std::enable_if<
117 std::is_same<typename std::result_of<F()>::type, void>::value,
119 makeTryFunction(F&& f);
124 #include <folly/wangle/Try-inl.h>