-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathInvoke.cpp
More file actions
90 lines (72 loc) · 2.42 KB
/
Invoke.cpp
File metadata and controls
90 lines (72 loc) · 2.42 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
83
84
85
86
87
88
89
90
// =====================================================================================
// Invoke.cpp // std::invoke
// =====================================================================================
module modern_cpp:invoke;
namespace StdInvoke {
// helper functions / classes
int add(int a, int b)
{
return a + b;
}
class Incrementer
{
public:
int m_x;
public:
Incrementer() : m_x{} {}
Incrementer(int x) : m_x{ x } {}
void incrementBy(int n) { m_x += n; }
void operator()() { std::cout << "m_x: " << m_x << std::endl; }
};
class TimesThree
{
public:
int operator()(int n) { return 3 * n; }
};
// testing scenarios for std::invoke
static void test_01()
{
int result{};
// free function:
result = std::invoke(add, 1, 2);
std::cout << "result: " << result << std::endl;
// => 3
// free function through pointer to function:
result = std::invoke(&add, 3, 4);
std::cout << "result: " << result << std::endl;
// => 7
int(*fadd) (int, int) { &add };
result = std::invoke(fadd, 5, 6);
std::cout << "result: " << result << std::endl;
// => 11
// member function through pointer to member function:
Incrementer inc{};
std::invoke(&Incrementer::incrementBy, &inc, 5);
inc(); // output
// => 5
// invoke (access) a (public) data member (!):
// C++20: useful for 'projections'
result = std::invoke(&Incrementer::m_x, &inc);
std::cout << "result: " << result << std::endl;
// (nested) function objects:
Incrementer inc2{ 10 };
result = std::invoke(std::plus<>(), std::invoke(&Incrementer::m_x, &inc2), 3);
std::cout << "result: " << result << std::endl;
// => 13
result = std::invoke(TimesThree{}, 5);
std::cout << "result: " << result << std::endl;
// => 15
// lambda expression:
result = std::invoke([](auto a, auto b) {return a + b; }, 11, 12);
std::cout << "result: " << result << std::endl;
// => 23
}
}
void main_invoke()
{
using namespace StdInvoke;
test_01();
}
// =====================================================================================
// End-of-File
// =====================================================================================