Last active
March 9, 2020 15:40
-
-
Save jroelofs/763907c6d02e25c17f73adba5b06ecb2 to your computer and use it in GitHub Desktop.
Inverted std::optional's
This file contains 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
// 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