blob: daf4502bd2b1997716cbc55be178d69c319cac1d [file] [log] [blame]
Dominik Laskowskia7e22552022-08-01 08:23:34 -07001/*
2 * Copyright 2022 The Android Open Source Project
3 *
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
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
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.
15 */
16
17#pragma once
18
19#include <functional>
20#include <optional>
21#include <type_traits>
22#include <utility>
23
24namespace android::ftl {
25
26// Superset of std::optional<T> with monadic operations, as proposed in https://wg21.link/P0798R8.
27//
28// TODO: Remove in C++23.
29//
30template <typename T>
31struct Optional final : std::optional<T> {
32 using std::optional<T>::optional;
33
34 using std::optional<T>::has_value;
35 using std::optional<T>::value;
36
37 // Returns Optional<U> where F is a function that maps T to U.
38 template <typename F>
39 constexpr auto transform(F&& f) const& {
40 using U = std::remove_cv_t<std::invoke_result_t<F, decltype(value())>>;
41 if (has_value()) return Optional<U>(std::invoke(std::forward<F>(f), value()));
42 return Optional<U>();
43 }
44
45 template <typename F>
46 constexpr auto transform(F&& f) & {
47 using U = std::remove_cv_t<std::invoke_result_t<F, decltype(value())>>;
48 if (has_value()) return Optional<U>(std::invoke(std::forward<F>(f), value()));
49 return Optional<U>();
50 }
51
52 template <typename F>
53 constexpr auto transform(F&& f) const&& {
54 using U = std::invoke_result_t<F, decltype(std::move(value()))>;
55 if (has_value()) return Optional<U>(std::invoke(std::forward<F>(f), std::move(value())));
56 return Optional<U>();
57 }
58
59 template <typename F>
60 constexpr auto transform(F&& f) && {
61 using U = std::invoke_result_t<F, decltype(std::move(value()))>;
62 if (has_value()) return Optional<U>(std::invoke(std::forward<F>(f), std::move(value())));
63 return Optional<U>();
64 }
65};
66
67// Deduction guide.
68template <typename T>
69Optional(T) -> Optional<T>;
70
71} // namespace android::ftl