| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
#pragma once |
| 5 |
|
| 6 |
#include <functional> |
| 7 |
#include <utility> |
| 8 |
#include <variant> |
| 9 |
|
| 10 |
namespace Common |
| 11 |
{ |
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
template <typename T> |
| 17 |
class Lazy |
| 18 |
{ |
| 19 |
public: |
| 20 |
Lazy() : m_value(T()) {} |
| 21 |
Lazy(const std::variant<T, std::function<T()>>& value) : m_value(value) {} |
| 22 |
Lazy(std::variant<T, std::function<T()>>&& value) : m_value(std::move(value)) {} |
| 23 |
const Lazy<T>& operator=(const std::variant<T, std::function<T()>>& value) |
| 24 |
{ |
| 25 |
m_value = value; |
| 26 |
return *this; |
| 27 |
} |
| 28 |
const Lazy<T>& operator=(std::variant<T, std::function<T()>>&& value) |
| 29 |
{ |
| 30 |
m_value = std::move(value); |
| 31 |
return *this; |
| 32 |
} |
| 33 |
const T& operator*() const { return *ComputeValue(); } |
| 34 |
const T* operator->() const { return ComputeValue(); } |
| 35 |
T& operator*() { return *ComputeValue(); } |
| 36 |
T* operator->() { return ComputeValue(); } |
| 37 |
|
| 38 |
private: |
| 39 |
T* ComputeValue() const |
| 40 |
{ |
| 41 |
if (!std::holds_alternative<T>(m_value)) |
| 42 |
m_value = std::get<std::function<T()>>(m_value)(); |
| 43 |
return &std::get<T>(m_value); |
| 44 |
} |
| 45 |
|
| 46 |
mutable std::variant<T, std::function<T()>> m_value; |
| 47 |
}; |
| 48 |
} |