-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmyFunction.cpp
More file actions
63 lines (53 loc) · 1.33 KB
/
myFunction.cpp
File metadata and controls
63 lines (53 loc) · 1.33 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
57
58
59
60
61
62
63
#include <iostream>
template <typename T>
class Function;
template <typename R, typename... Args>
class Function<R(Args...)> {
private:
struct MainCallable {
virtual R call(Args... args) = 0;
virtual ~MainCallable() = default;
};
template <typename F>
struct Callable : MainCallable {
F f;
Callable(F&& f_) : f(std::forward<F>(f_)) {};
virtual R call(Args... args) override {
return f(args...);
}
};
public:
Function() = default;
template <typename F>
Function(F&& f) {
using U = std::decay_t<F>;
ptr = new Callable(std::forward<U>(f));
}
~Function() {
delete ptr;
}
R operator()(Args&&... args) {
return ptr->call(std::forward<Args>(args)...);
}
MainCallable* ptr = nullptr;
};
struct A {
auto operator()(int a, int b) -> int{
return a + b;
}
};
int func(int a, int b) {
return a + b;
}
int main() {
auto lam = [](int a, int b) -> int{
return a + b;
};
Function<int(int, int)> f(lam);
A a{};
Function<int(int, int)> ff(a);
Function<int(int, int)> fff(func);
std::cout << f(2, 3);
std::cout << ff(2, 3);
std::cout << fff(2, 3);
}