1 #ifndef C10_UTIL_OPTIONAL_H_
2 #define C10_UTIL_OPTIONAL_H_
3
4 #include <optional>
5 #include <type_traits>
6
7 // Macros.h is not needed, but it does namespace shenanigans that lots
8 // of downstream code seems to rely on. Feel free to remove it and fix
9 // up builds.
10
11 namespace c10 {
12 // NOLINTNEXTLINE(misc-unused-using-decls)
13 using std::bad_optional_access;
14 // NOLINTNEXTLINE(misc-unused-using-decls)
15 using std::make_optional;
16 // NOLINTNEXTLINE(misc-unused-using-decls)
17 using std::nullopt;
18 // NOLINTNEXTLINE(misc-unused-using-decls)
19 using std::nullopt_t;
20 // NOLINTNEXTLINE(misc-unused-using-decls)
21 using std::optional;
22
23 namespace detail_ {
24 // the call to convert<A>(b) has return type A and converts b to type A iff b
25 // decltype(b) is implicitly convertible to A
26 template <class U>
convert(U v)27 constexpr U convert(U v) {
28 return v;
29 }
30 } // namespace detail_
31 template <class T, class F>
value_or_else(const std::optional<T> & v,F && func)32 constexpr T value_or_else(const std::optional<T>& v, F&& func) {
33 static_assert(
34 std::is_convertible_v<typename std::invoke_result_t<F>, T>,
35 "func parameters must be a callable that returns a type convertible to the value stored in the optional");
36 return v.has_value() ? *v : detail_::convert<T>(std::forward<F>(func)());
37 }
38
39 template <class T, class F>
value_or_else(std::optional<T> && v,F && func)40 constexpr T value_or_else(std::optional<T>&& v, F&& func) {
41 static_assert(
42 std::is_convertible_v<typename std::invoke_result_t<F>, T>,
43 "func parameters must be a callable that returns a type convertible to the value stored in the optional");
44 return v.has_value() ? constexpr_move(std::move(v).contained_val())
45 : detail_::convert<T>(std::forward<F>(func)());
46 }
47 } // namespace c10
48 #endif // C10_UTIL_OPTIONAL_H_
49