-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmake_lazy.cpp
More file actions
56 lines (51 loc) · 1.03 KB
/
make_lazy.cpp
File metadata and controls
56 lines (51 loc) · 1.03 KB
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <iostream>
#include <optional>
#include <type_traits>
#include <functional>
#include <vector>
#include <string>
template<typename F>
class lazy;
template<typename F>
lazy<F> make_lazy(F&&_r);
template<typename F>
class lazy
{ public:
#ifdef __cplusplus > 201703L
typedef typename std::invoke_result<F>::type type;
#else
typedef typename std::decay<decltype(std::declval<F>()())>::type type;
#endif
private:
std::optional<type> m_sO;
F m_sF;
public:
lazy(F &&_r)
:m_sF(std::move(_r))
{
}
type &get(void)
{ if (!m_sO)
m_sO.emplace(m_sF());
return *m_sO;
}
friend lazy<F> make_lazy(F&&_r);
};
template<typename F>
lazy<F> make_lazy(F&&_r)
{ return lazy<F>(std::move(_r));
}
int main(int argc, char**argv)
{
auto sLazy = make_lazy(
[](void)
{ /// something expensive which one only wants to do
/// if really necessary
/// potentially reading a file and returning the contents
return std::vector<std::string>();
}
);
if (argc > 1)
const auto &sLines = sLazy.get();
std::cout << "Hello World!\n";
}