Skip to content

Instantly share code, notes, and snippets.

@sigman78
Created May 7, 2019 12:18
Show Gist options
  • Save sigman78/a1ea8f142f57c5c974e31b53303c91ea to your computer and use it in GitHub Desktop.
Save sigman78/a1ea8f142f57c5c974e31b53303c91ea to your computer and use it in GitHub Desktop.
Draft of optional{float} for safe nan usage
#include <cmath>
#include <limits>
struct float_opt
{
float value_ = std::numeric_limits<float>::quiet_NaN();
explicit float_opt(float v): value_(v) {}
constexpr float_opt() = default;
constexpr float unwrap() const { return value_; }
bool valid() const { return !std::isnan(value_); }
bool empty() const { return std::isnan(value_); }
};
inline bool operator==(float_opt lhs, float_opt rhs) {
return lhs.unwrap() == rhs.unwrap() || (lhs.empty() && rhs.empty());
}
inline bool operator!=(float_opt lhs, float_opt rhs) {
return !(lhs == rhs);
}
inline bool operator==(float_opt lhs, float rhs) {
return lhs == float_opt{rhs};
}
inline bool operator!=(float_opt lhs, float rhs) {
return !(lhs == rhs);
}
inline bool operator==(float lhs, float_opt rhs) {
return float_opt{lhs} == rhs;
}
inline bool operator!=(float lhs, float_opt rhs) {
return !(lhs == rhs);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment