Created
January 28, 2016 06:46
-
-
Save PhDP/4abf920e282a9a9df49d to your computer and use it in GitHub Desktop.
Example of boost::optional to write a safe sqrt function.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// clang++ -std=c++11 safe_sqrt.cc | |
#include <iostream> | |
#include <cmath> | |
#include <boost/optional.hpp> | |
auto safe_sqrt(double x) -> boost::optional<double> { | |
if (x >= 0.0) | |
return std::sqrt(x); | |
return boost::none; | |
} | |
auto main() -> int { | |
const auto xs = std::vector<double> { -0.001, 0.5, 23333.9182, -78.0183 }; | |
for (const auto x : xs) { | |
const auto s = safe_sqrt(x); | |
if (s) | |
std::cout << "sqrt(" << x << ") = " << *s << '\n'; | |
else | |
std::cout << "No square roots for " << x << " on the real line.\n"; | |
} | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment