Support mapping functions which return references

This commit is contained in:
Simon Brand
2017-12-05 19:51:20 +00:00
parent 5a3f094ec7
commit 247677394f
2 changed files with 9 additions and 3 deletions

View File

@@ -1595,7 +1595,7 @@ template <class Opt, class F,
constexpr auto map_impl(Opt &&opt, F &&f) {
return opt.has_value()
? detail::invoke(std::forward<F>(f), *std::forward<Opt>(opt))
: optional<Ret>(nullopt);
: optional<detail::decay_t<Ret>>(nullopt);
}
template <class Opt, class F,
@@ -1616,10 +1616,10 @@ template <class Opt, class F,
*std::declval<Opt>())),
detail::enable_if_t<!std::is_void<Ret>::value> * = nullptr>
constexpr auto map_impl(Opt &&opt, F &&f) -> optional<Ret> {
constexpr auto map_impl(Opt &&opt, F &&f) -> optional<detail::decay_t<Ret>> {
return opt.has_value()
? detail::invoke(std::forward<F>(f), *std::forward<Opt>(opt))
: optional<Ret>(nullopt);
: optional<detail::decay_t<Ret>>(nullopt);
}
template <class Opt, class F,

View File

@@ -119,6 +119,12 @@ TEST_CASE("Monadic operations", "[monadic]") {
const tl::optional<int> o37 = tl::nullopt;
auto o37r = std::move(o37).map([](int) { return; });
REQUIRE(!o37r);
// callable which returns a reference
tl::optional<int> o38 = 42;
auto o38r = o38.map([](int& i) -> const int& { return i; });
REQUIRE(o38r);
REQUIRE(*o38r == 42);
}
SECTION("map constexpr") {