mirror of
https://github.com/trafi/maybe-result-cpp
synced 2024-11-26 04:26:06 +01:00
Use crazy magic and infer returned result type from return type of lambda.
This commit is contained in:
parent
2cf23a45e4
commit
9b2c4842ae
@ -193,8 +193,8 @@ namespace maybe {
|
||||
return std::addressof(err_val);
|
||||
}
|
||||
|
||||
template <typename R>
|
||||
constexpr result<R, E> map(std::function<R(T v)> closure) noexcept;
|
||||
template <typename F>
|
||||
constexpr auto map(F f) noexcept -> maybe::result<decltype(f(std::declval<T>())), E>;
|
||||
|
||||
private:
|
||||
constexpr void copy_from(const result<T, E>& other) noexcept;
|
||||
|
@ -97,11 +97,14 @@ constexpr void maybe::result<T, E>::clear() noexcept
|
||||
}
|
||||
|
||||
template <typename T, typename E>
|
||||
template <typename R>
|
||||
constexpr maybe::result<R, E> maybe::result<T, E>::map(std::function<R(T v)> closure) noexcept
|
||||
template <typename F>
|
||||
constexpr auto maybe::result<T, E>::map(F f) noexcept
|
||||
-> maybe::result<decltype(f(std::declval<T>())), E>
|
||||
{
|
||||
typedef maybe::result<decltype(f(std::declval<T>())), E> return_result_t;
|
||||
|
||||
if (is_err()) {
|
||||
return maybe::result<R, E>::err(err_value());
|
||||
return return_result_t::err(std::forward<E>(err_value()));
|
||||
}
|
||||
return maybe::result<R, E>::ok(closure(ok_value()));
|
||||
return return_result_t::ok(f(std::forward<T>(ok_value())));
|
||||
};
|
@ -21,7 +21,7 @@ TEST_CASE("result_chaining")
|
||||
SECTION("converts result A to result B")
|
||||
{
|
||||
auto a = result<A, int>::ok(A("hello"));
|
||||
auto b = a.map<B>([](const A& v) { return B(v.value); });
|
||||
auto b = a.map([](A v) { return B(v.value); });
|
||||
REQUIRE(b);
|
||||
REQUIRE(b.ok_value().value == "hello");
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user