-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathmain.cpp
More file actions
82 lines (64 loc) · 1.23 KB
/
main.cpp
File metadata and controls
82 lines (64 loc) · 1.23 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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include <iostream>
class Bar;
template<bool IsConst>
using Handler = typename
std::conditional_t
<
IsConst
, std::function<void(Bar const*)>
, std::function<void(Bar*) >
>;
class Bar
{
public:
void Handle() const
{
m_handlerConst(this);
}
void HandleIfPresent() const
{
if (m_handlerConst)
m_handlerConst(this);
}
void Handle()
{
m_handler(this);
}
void HandleIfPresent()
{
if (m_handler)
m_handler(this);
}
void SetHandler(Handler<true>&& aHandler)
{
m_handlerConst = std::move(aHandler);
}
void SetHandler(Handler<false>&& aHandler)
{
m_handler = std::move(aHandler);
}
private:
Handler<true> m_handlerConst;
Handler<false> m_handler;
};
void test1()
{
Bar const b;
b.HandleIfPresent(); // OK
b.Handle(); // BAD
// libc++abi: terminating with uncaught exception of type std::__1::bad_function_call: std::exception
}
void test2()
{
Bar b;
b.HandleIfPresent(); // OK
b.SetHandler([](Bar*) {
std::cout << "Hello, World!" << std::endl;
});
b.Handle();
}
int main()
{
test2();
return 0;
}