Simple-Utility v2.3.1
Loading...
Searching...
No Matches
and_then.hpp
Go to the documentation of this file.
1// Copyright Dominic Koepke 2019 - 2023.
2// Distributed under the Boost Software License, Version 1.0.
3// (See accompanying file LICENSE_1_0.txt or copy at
4// https://www.boost.org/LICENSE_1_0.txt)
5
6#ifndef SL_UTILITY_NULLABLES_AND_THEN_HPP
7#define SL_UTILITY_NULLABLES_AND_THEN_HPP
8
9#pragma once
10
13
14namespace sl::nullables::detail
15{
16 template <input_nullable TInputNullable, std::invocable<dereference_result_t<TInputNullable>> TFunc>
17 requires nullable<std::invoke_result_t<TFunc, dereference_result_t<TInputNullable>>>
18 [[nodiscard]]
19 constexpr std::invoke_result_t<TFunc, dereference_result_t<TInputNullable>> and_then(TInputNullable&& inputNullable, TFunc&& func)
20 {
21 using result_nullable_t = std::invoke_result_t<TFunc, dereference_result_t<TInputNullable>>;
22
23 if (inputNullable != null_v<TInputNullable>)
24 {
25 return std::invoke(std::forward<TFunc>(func), unwrap(std::forward<TInputNullable>(inputNullable)));
26 }
27 return result_nullable_t{null_v<result_nullable_t>};
28 }
29
30 class and_then_caller_fn
31 {
32 public:
33 template <input_nullable TInputNullable, std::invocable<dereference_result_t<TInputNullable>> TFunc>
34 requires nullable<std::invoke_result_t<TFunc, dereference_result_t<TInputNullable>>>
35 [[nodiscard]]
36 constexpr auto operator ()(
37 TInputNullable&& inputNullable,
38 TFunc&& func
39 ) const
40 noexcept(noexcept(and_then(std::declval<TInputNullable>(), std::declval<TFunc>())))
41 {
42 return and_then(
43 std::forward<TInputNullable>(inputNullable),
44 std::forward<TFunc>(func));
45 }
46 };
47}
48
49namespace sl::nullables
50{
79 inline constexpr auto and_then = []<class Fn>(Fn&& fn) noexcept(std::is_nothrow_constructible_v<std::remove_cvref_t<Fn>, Fn>)
80 {
81 return Algorithm{functional::bind_back(detail::and_then_caller_fn{}, std::forward<Fn>(fn))};
82 };
83
85}
86
87#endif
The core algorithm helper, which executes the held operation when used as the right-hand-side of oper...
Definition: base.hpp:216
constexpr auto bind_back
Helper function, which generates a forwarding call wrapper for the given function and curries the par...
Definition: bind_back.hpp:100
constexpr auto and_then
Passes the value of the input_nullable to the function if it's not equal to its null-object....
Definition: and_then.hpp:79
constexpr detail::unwrap_fn unwrap
Retrieves the value of the given input_nullable.
Definition: base.hpp:160
Definition: adapter.hpp:19