Skip to content

Instantly share code, notes, and snippets.

@PhDP
Created January 28, 2016 06:46
Show Gist options
  • Save PhDP/4abf920e282a9a9df49d to your computer and use it in GitHub Desktop.
Save PhDP/4abf920e282a9a9df49d to your computer and use it in GitHub Desktop.
Example of boost::optional to write a safe sqrt function.
// 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