Created
January 11, 2017 00:28
-
-
Save joelgallant/e1511670be07268128836d629478c04d to your computer and use it in GitHub Desktop.
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
template <typename T> | |
class Optional final { | |
struct NullOption { | |
explicit constexpr NullOption(int) {} // NOLINT | |
}; | |
public: | |
Optional() : has_val(false), val() { } | |
Optional(NullOption) : has_val(false), val() { } // NOLINT | |
Optional(T val) : has_val(true), val(val) { } // NOLINT | |
inline bool has_value() const { return has_val; } | |
inline explicit operator bool() const { return has_value(); } | |
inline T value() const { | |
if (!has_value()) { | |
throw std::runtime_error("bad optional access"); | |
} else { | |
return val; | |
} | |
} | |
inline T& value() { | |
if (!has_value()) { | |
throw std::runtime_error("bad optional access"); | |
} else { | |
return val; | |
} | |
} | |
inline T value_or(T def) const { return has_value() ? val : def; } | |
inline T operator*() const { return value(); } | |
inline T& operator*() { return val; } | |
inline void clear() { has_val = false; } | |
inline bool matches(const Optional<T>& m) const { | |
return (has_value() && m.has_value()) ? m.value() == value() : true; | |
} | |
private: | |
bool has_val; | |
T val; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment