Simple-Utility v2.3.1
Loading...
Searching...
No Matches
or_else.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_OR_ELSE_HPP
7#define SL_UTILITY_NULLABLES_OR_ELSE_HPP
8
9#pragma once
10
13
14namespace sl::nullables::detail
15{
16 template <nullable TNullable, std::invocable TFunc>
17 requires std::is_void_v<std::invoke_result_t<TFunc>>
18 || std::constructible_from<std::remove_cvref_t<TNullable>, std::invoke_result_t<TFunc>>
19 [[nodiscard]]
20 constexpr std::remove_cvref_t<TNullable> or_else(TNullable&& nullableObj, TFunc&& func)
21 {
22 using result_t = std::remove_cvref_t<TNullable>;
23
24 if (nullableObj == null_v<TNullable>)
25 {
26 if constexpr (std::is_void_v<std::invoke_result_t<TFunc>>)
27 {
28 std::invoke(std::forward<TFunc>(func));
29 return result_t{ null_v<TNullable> };
30 }
31 else
32 {
33 return result_t{ std::invoke(std::forward<TFunc>(func)) };
34 }
35 }
36 return std::forward<TNullable>(nullableObj);
37 }
38
39 class or_else_caller_fn
40 {
41 public:
42 template <nullable TNullable, std::invocable TFunc>
43 [[nodiscard]]
44 constexpr std::remove_cvref_t<TNullable> operator ()
45 (
46 TNullable&& nullableObj,
47 TFunc&& func
48 ) const
49 noexcept(noexcept(or_else(std::declval<TNullable>(), std::declval<TFunc>())))
50 {
51 return or_else(
52 std::forward<TNullable>(nullableObj),
53 std::forward<TFunc>(func)
54 );
55 }
56 };
57}
58
59namespace sl::nullables
60{
90 inline constexpr auto or_else = []<class Fn>(Fn&& fn) noexcept(std::is_nothrow_constructible_v<std::remove_cvref_t<Fn>, Fn>)
91 {
92 return Algorithm{functional::bind_back(detail::or_else_caller_fn{}, std::forward<Fn>(fn))};
93 };
94
96}
97
98#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 or_else
Returns the nullable if it's not equal to its ''null''-object. Executes the passed function otherwise...
Definition: or_else.hpp:90
Definition: adapter.hpp:19