diff --git a/nui/include/nui/utility/lazy.hpp b/nui/include/nui/utility/lazy.hpp new file mode 100644 index 00000000..0c5c1c8c --- /dev/null +++ b/nui/include/nui/utility/lazy.hpp @@ -0,0 +1,73 @@ +#pragma once + +#include +#include + +namespace Nui +{ + template + class Lazy + { + public: + Lazy() = default; + Lazy(Lazy const&) = default; + Lazy(Lazy&&) = default; + Lazy& operator=(Lazy const&) = default; + Lazy& operator=(Lazy&&) = default; + + template + Lazy(FuncT&& func) + : value_{} + , obtainer_{std::forward(func)} + {} + + explicit operator bool() const + { + return value_.has_value(); + } + + bool hasValue() const + { + return value_.has_value(); + } + + bool tryObtainValue() const + { + if (!value_) + value_ = obtainer_(); + return hasValue(); + } + + std::optional const& value() const& + { + if (!value_) + value_ = obtainer_(); + return value_; + } + + std::optional&& value() && + { + if (!value_) + value_ = obtainer_(); + return std::move(value_); + } + + std::optional value() const&& + { + if (!value_) + value_ = obtainer_(); + return value_; + } + + std::optional& value() & + { + if (!value_) + value_ = obtainer_(); + return value_; + } + + private: + std::optional value_{}; + std::function()> obtainer_{}; + }; +} \ No newline at end of file