X-Git-Url: https://git.stg.codes/stg.git/blobdiff_plain/e5499c61083684b28bcbc6950aae66cbf0938703..e9ae1f101b5418c0ba2e6c9d86b23c12f0140982:/include/stg/optional.h diff --git a/include/stg/optional.h b/include/stg/optional.h new file mode 100644 index 00000000..105d7e2f --- /dev/null +++ b/include/stg/optional.h @@ -0,0 +1,54 @@ +#pragma once + +namespace STG +{ + +template +class Optional +{ +public: + using value_type = T; + + Optional() noexcept : m_isSet(false) {} + explicit Optional(const T& value) noexcept : m_value(value), m_isSet(true) {} + + Optional(const Optional&) = default; + Optional& operator=(const Optional&) = default; + + Optional(Optional&&) = default; + Optional& operator=(Optional&&) = default; + + Optional& operator=(const T & rhs) noexcept + { + m_value = rhs; + m_isSet = true; + return *this; + } + + const T & const_data() const noexcept { return m_value; } + T & data() noexcept { return m_value; } + const T & data() const noexcept { return m_value; } + bool empty() const noexcept { return !m_isSet; } + void reset() noexcept { m_isSet = false; } + void splice(const Optional& rhs) noexcept + { + if (rhs.m_isSet) + { + m_value = rhs.m_value; + m_isSet = true; + } + } + const T& get(const T& defaultValue) const noexcept + { + if (m_isSet) + return m_value; + else + return defaultValue; + } + +private: + value_type m_value; + bool m_isSet; +}; + +}