-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathex1.cpp
84 lines (66 loc) · 1.73 KB
/
ex1.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
/*
"`for_each_arg` explained and expanded"
C++Now 2015 Lightning Talk
- Vittorio Romeo
http://vittorioromeo.info
vittorio.romeo@outlook.com
*/
// The files used in this talk are available at:
/*
https://github.com/SuperV1234/cppnow2015
*/
#include <iostream>
template <typename TF, typename... Ts>
void forArgs(TF&& mFn, Ts&&... mArgs)
{
// We use an `initializer_list` to create a context
// where variadic parameter expansion can take place.
return (void)std::initializer_list<int>{
// Every element of the `initializer_list` is an
// expression enclosed in round parenthesis.
(
// In the parenthesis, the result of the `mFn`
// function call is followed by the comma
// operator and an integer (zero in this
// case).
// Thanks to the comma operator, the expression
// evaluates to an (unused) integer, which is
// accepted by the `initializer_list`.
mFn(std::forward<Ts>(mArgs)),
0)...};
}
/*
// The following `forArgs` call...
forArgs
(
[](const auto& x){ std::cout << x << " "; },
"hello",
1,
2,
3
);
// ..roughly expands to...
(void) std::initializer_list<int>
{
([](const auto& x){ std::cout << x; }("hello"), 0),
([](const auto& x){ std::cout << x; }(1), 0),
([](const auto& x){ std::cout << x; }(2), 0),
([](const auto& x){ std::cout << x; }(3), 0)
}
// ...which is the same as writing...
std::cout << "hello";
std::cout << 1;
std::cout << 2;
std::cout << 3;
*/
int main()
{
// Prints "hello 1 2 3".
forArgs(
[](const auto& x)
{
std::cout << x << " ";
},
"hello", 1, 2, 3);
return 0;
}