forked from hsf-training/cpluspluscourse
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoptional.cpp
37 lines (29 loc) · 782 Bytes
/
optional.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
/*
In the code below, modify the function `mysqrt` below so that it returns
an `std::optional<double>` rather than a double, and the program prints
`nothing` rather than `nan` for the call with `-10`. It will also require
to modify `square`.
*/
#include <cmath>
#include <iostream>
#include <optional>
double mysqrt(double d) // TO BE MODIFIED
{
return std::sqrt(d); // TO BE MODIFIED
}
double square(double d) // TO BE MODIFIED
{
return d * d; // TO BE MODIFIED
}
template <typename A>
std::ostream &operator<<(std::ostream &os, std::optional<A> const &opt) {
if (opt) {
return os << opt.value();
} else {
return os << "nothing";
}
}
int main() {
std::cout << square(mysqrt(10)) << std::endl;
std::cout << square(mysqrt(-10)) << std::endl;
}