forked from NuiCpp/Nui
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request NuiCpp#104 from NuiCpp/devel
Added lazy loading wrapper.
- Loading branch information
Showing
1 changed file
with
73 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
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_{}; | ||
}; | ||
} |