Skip to content

Commit

Permalink
Added lazy loading wrapper.
Browse files Browse the repository at this point in the history
  • Loading branch information
5cript committed Jan 15, 2024
1 parent 73485d7 commit 3835d2f
Showing 1 changed file with 73 additions and 0 deletions.
73 changes: 73 additions & 0 deletions nui/include/nui/utility/lazy.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
#pragma once

#include <optional>
#include <functional>

namespace Nui
{
template <typename ValueT>
class Lazy
{
public:
Lazy() = default;
Lazy(Lazy const&) = default;
Lazy(Lazy&&) = default;
Lazy& operator=(Lazy const&) = default;
Lazy& operator=(Lazy&&) = default;

template <typename FuncT>
Lazy(FuncT&& func)
: value_{}
, obtainer_{std::forward<FuncT>(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<ValueT> const& value() const&
{
if (!value_)
value_ = obtainer_();
return value_;
}

std::optional<ValueT>&& value() &&
{
if (!value_)
value_ = obtainer_();
return std::move(value_);
}

std::optional<ValueT> value() const&&
{
if (!value_)
value_ = obtainer_();
return value_;
}

std::optional<ValueT>& value() &
{
if (!value_)
value_ = obtainer_();
return value_;
}

private:
std::optional<ValueT> value_{};
std::function<std::optional<ValueT>()> obtainer_{};
};
}

0 comments on commit 3835d2f

Please sign in to comment.