forked from qicosmos/cosmos
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Lazy.hpp
37 lines (32 loc) · 757 Bytes
/
Lazy.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#pragma once
#include <Optional.hpp>
template<typename T>
struct Lazy
{
template <typename Func, typename... Args>
Lazy(Func& f, Args && ... args)
{
m_func = [&f, &args...]{return f(args...); };
}
T& Value()
{
if (!m_value.IsInit())
{
m_value = m_func();
}
return *m_value;
}
bool IsValueCreated() const
{
return m_value.IsInit();
}
private:
std::function<T()> m_func;
Optional<T> m_value;
};
template<class Func, typename... Args>
Lazy<typename std::result_of<Func(Args...)>::type>
lazy(Func && fun, Args && ... args)
{
return Lazy<typename std::result_of<Func(Args...)>::type>(std::forward<Func>(fun), std::forward<Args>(args)...);
}