-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstd_function.cpp
88 lines (72 loc) · 1.45 KB
/
std_function.cpp
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#include <iostream>
#include <memory>
using std::cout;
namespace pjr
{
template<typename>
class function;
template<typename R, typename... Args>
class function<R(Args...)>
{
struct concept
{
virtual ~concept() = default;
virtual R invoke(Args&&...) = 0;
};
template <typename F>
struct model : public concept
{
model(F&& fn) : _fn(std::forward<F>(fn)) {}
R invoke(Args&&... args) override
{
return _fn(std::forward<Args>(args)...);
}
private:
F _fn;
};
std::unique_ptr<concept> _stored;
public:
using result_type = R;
template<typename F>
function(F&& fn)
{
_stored = std::make_unique<model<F>>(std::forward<F>(fn));
}
R operator()(Args... args)
{
return _stored->invoke(std::forward<Args>(args)...);
}
};
}
void foo()
{
cout << "foo\n";
}
void bar(int)
{
cout << "bar\n";
}
int baz(int)
{
cout << "baz\n";
return 1;
}
struct functor
{
void operator()()
{
cout << "functor\n";
}
};
int main()
{
using pjr::function;
function<void()> f1 = foo;
function<void(int)> f2 = bar;
function<int(int)> f3 = baz;
function<void()> f4 = [](){ cout << "lambda\n"; };
f1();
f2(1);
int ret = f3(2);
f4();
}