From 9b2c4842ae9cf83cf76272a441e46d74f726b4de Mon Sep 17 00:00:00 2001 From: Nerijus Arlauskas Date: Wed, 6 Jul 2016 20:47:34 +0300 Subject: [PATCH] Use crazy magic and infer returned result type from return type of lambda. --- src/maybe/result.hpp | 4 ++-- src/maybe/result.inline.hpp | 11 +++++++---- tests/result_chaining_tests.cpp | 2 +- 3 files changed, 10 insertions(+), 7 deletions(-) diff --git a/src/maybe/result.hpp b/src/maybe/result.hpp index ce77c43..bfa8d57 100644 --- a/src/maybe/result.hpp +++ b/src/maybe/result.hpp @@ -193,8 +193,8 @@ namespace maybe { return std::addressof(err_val); } - template - constexpr result map(std::function closure) noexcept; + template + constexpr auto map(F f) noexcept -> maybe::result())), E>; private: constexpr void copy_from(const result& other) noexcept; diff --git a/src/maybe/result.inline.hpp b/src/maybe/result.inline.hpp index 51c6cbe..b00cf5c 100644 --- a/src/maybe/result.inline.hpp +++ b/src/maybe/result.inline.hpp @@ -97,11 +97,14 @@ constexpr void maybe::result::clear() noexcept } template -template -constexpr maybe::result maybe::result::map(std::function closure) noexcept +template +constexpr auto maybe::result::map(F f) noexcept + -> maybe::result())), E> { + typedef maybe::result())), E> return_result_t; + if (is_err()) { - return maybe::result::err(err_value()); + return return_result_t::err(std::forward(err_value())); } - return maybe::result::ok(closure(ok_value())); + return return_result_t::ok(f(std::forward(ok_value()))); }; \ No newline at end of file diff --git a/tests/result_chaining_tests.cpp b/tests/result_chaining_tests.cpp index 56052c0..399361f 100644 --- a/tests/result_chaining_tests.cpp +++ b/tests/result_chaining_tests.cpp @@ -21,7 +21,7 @@ TEST_CASE("result_chaining") SECTION("converts result A to result B") { auto a = result::ok(A("hello")); - auto b = a.map([](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"); }