forked from BowenFu/matchit.cpp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoptionalLift.cpp
More file actions
30 lines (28 loc) · 742 Bytes
/
optionalLift.cpp
File metadata and controls
30 lines (28 loc) · 742 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include "matchit.h"
#include <iostream>
#include <optional>
// lift a function from T -> U to std::optional<T> -> std::optional<U>
template <typename Func>
auto optionalLift(Func func)
{
using namespace matchit;
return [func](auto &&v)
{
Id<std::decay_t<decltype(*v)>> x;
using RetType = decltype(std::make_optional(func(*x)));
return match(v)(
// clang-format off
pattern | some(x) = [&] { return std::make_optional(func(*x)); },
pattern | none = RetType{}
// clang-format on
);
};
}
int32_t main()
{
auto const func = [](auto &&e)
{ return e * e; };
auto const result = optionalLift(func)(std::make_optional(2));
std::cout << *result << std::endl;
return 0;
}