Skip to content

Commit

Permalink
Merge pull request NuiCpp#104 from NuiCpp/devel
Browse files Browse the repository at this point in the history
Added lazy loading wrapper.
  • Loading branch information
5cript authored Jan 16, 2024
2 parents 4cb4cbc + 3835d2f commit 9e7e3f0
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 9e7e3f0

Please sign in to comment.