Created
October 5, 2017 14:45
-
-
Save xaedes/ff661bf9bf7d488c66264a99449b079a to your computer and use it in GitHub Desktop.
Maybe<T> statically typed and allocated Maybe type for C++
This file contains hidden or 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 Maybe | |
{ | |
public: | |
static Maybe Just(const T& just) | |
{ | |
return Maybe(just); | |
} | |
static Maybe Just() | |
{ | |
T empty; | |
return Maybe(empty); | |
} | |
static Maybe Nothing() | |
{ | |
return Maybe(); | |
} | |
Maybe(const Maybe<T>& copyFrom) | |
: m_valid(false) | |
{ | |
if(copyFrom) | |
{ | |
just(copyFrom.value()); | |
} | |
} | |
Maybe(const T& just) | |
: m_value(just) | |
, m_valid(true) | |
{} | |
Maybe() | |
: m_valid(false) | |
{} | |
~Maybe() | |
{} | |
const T& value() const | |
{ | |
return m_value; | |
} | |
T* ptr() | |
{ | |
if (m_valid) | |
{ | |
return &m_value; | |
} | |
else | |
{ | |
return nullptr; | |
} | |
} | |
const T* operator->() const | |
{ | |
if (m_valid) | |
{ | |
return &m_value; | |
} | |
else | |
{ | |
return nullptr; | |
} | |
} | |
T* operator->() | |
{ | |
if (m_valid) | |
{ | |
return &m_value; | |
} | |
else | |
{ | |
return nullptr; | |
} | |
} | |
explicit operator bool() const | |
{ | |
return containsValue(); | |
} | |
bool containsNothing() const | |
{ | |
return !m_valid; | |
} | |
bool containsValue() const | |
{ | |
return m_valid; | |
} | |
bool isValid() const | |
{ | |
return m_valid; | |
} | |
bool isEmpty() const | |
{ | |
return !m_valid; | |
} | |
void clear() | |
{ | |
T empty; | |
m_value = empty; | |
m_valid = false; | |
} | |
T& just(const T& just) | |
{ | |
m_valid = true; | |
m_value = just; | |
return m_value; | |
} | |
T& just() | |
{ | |
m_valid = true; | |
return m_value; | |
} | |
protected: | |
bool m_valid; | |
T m_value; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment