Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <exception>
- #include <string>
- class Panic: public std::exception {
- public:
- Panic(const char *err): msg(err) {}
- virtual const char* what() const noexcept { return msg.c_str(); }
- private:
- std::string msg;
- };
- template<typename T>
- class Option {
- private:
- T m_Obj;
- bool m_Is_Some;
- public:
- Option(T*, bool);
- static Option<T> Some(T);
- static Option<T> None();
- T unwrap();
- bool is_some();
- bool is_none();
- };
- template<typename T>
- Option<T>::Option(T *object, bool is_some) {
- if (is_some) {
- m_Obj = *object;
- }
- m_Is_Some = is_some;
- }
- template<typename T>
- Option<T> Option<T>::Some(T object) {
- return Option(&object, true);
- }
- template<typename T>
- Option<T> Option<T>::None() {
- return Option(nullptr, false);
- }
- template<typename T>
- T Option<T>::unwrap() {
- if (!m_Is_Some) {
- throw Panic("Option::unwrap() called on 'None' value");
- }
- return m_Obj;
- }
- template<typename T>
- bool Option<T>::is_some() {
- return m_Is_Some;
- }
- template<typename T>
- bool Option<T>::is_none() {
- return !m_Is_Some;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement