-
Notifications
You must be signed in to change notification settings - Fork 0
/
fp_optional_bind.cpp
41 lines (33 loc) · 990 Bytes
/
fp_optional_bind.cpp
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
31
32
33
34
35
36
37
38
39
40
41
#include <iostream>
#include <optional>
#include <cmath>
using std::optional;
template <typename T, typename funcType> auto operator>>=(funcType &&f, const optional<T>& x)
{
if (x) { return f(x.value()); }
else { return decltype(f(std::declval<T>())){}; }
}
inline std::ostream& operator<<(std::ostream& os, const optional<double>& x)
{
if (x) { os << "Value: " << x.value() << std::endl; }
else { os << "No value" << std::endl; }
return os;
}
optional<double> squareRoot(double x)
{
if (x >= 0) { return sqrt(x); }
else { return {}; }
}
optional<double> divide(double x, double y)
{
if (y != 0) { return x / y; }
else { return {}; }
}
int main(int, char **)
{
std::cout << (squareRoot >>= optional<double>(16.));
std::cout << (squareRoot >>= optional<double>(-10.));
std::cout << (squareRoot >>= optional<double>());
std::cout << ([](auto x){return divide(x, 2.);} >>= optional<double>(10.));
return 0;
}