Skip to content

Instantly share code, notes, and snippets.

@jroelofs
Last active March 9, 2020 15:40
Show Gist options
  • Save jroelofs/763907c6d02e25c17f73adba5b06ecb2 to your computer and use it in GitHub Desktop.
Save jroelofs/763907c6d02e25c17f73adba5b06ecb2 to your computer and use it in GitHub Desktop.
Inverted std::optional's
// Utility that makes it a little bit nicer to
// invert the condition on assignment from optional:
// if ((Not{foo} = maybeMakeFoo()) {
// std::cerr << "can't make foo\n";
// }
#include <optional>
template<typename T>
struct Not {
explicit Not(T &V) : V(V), HasVal(false) {}
Not<T> &operator=(const std::optional<T> &RHS) {
if (RHS.has_value()) { HasVal = true; V = *RHS; }
return *this;
}
explicit operator bool() const { return !HasVal; }
T &V;
mutable bool HasVal;
};
int if_then() {
int foo;
if ((Not{foo} = std::nullopt)) {
return 42;
}
return 0;
}
int if_else() {
int foo;
if ((Not{foo} = 42)) {
return 42;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment