First commit
[cpp_sandbox.git] / Sandbox / Bind.cpp
1 #include "Bind.h"
2
3 #include <iostream>
4 #include <functional>
5 using namespace std;
6
7 // https://en.cppreference.com/w/cpp/utility/functional/bind
8 // Ep 15: https://www.youtube.com/watch?v=JtUZmkvroKg & https://www.youtube.com/watch?v=ZlHi8txU4aQ
9
10 namespace Bind
11 {
12 template <typename T>
13 void print(T i, const string& s)
14 {
15 cout << i << ' ' << s << endl;
16 }
17
18 void bind()
19 {
20 int i = 5;
21
22 // The given function must be a concrete one (the generic parameter of 'print' must be specified in this case).
23 // 'ref' is to create a standard reference to 'i'.
24 // the second parameter create a parameter in the new created function.
25 // 'bind' were originaly from the Boost library.
26 const auto f = bind(&print<int>, ref(i), placeholders::_1);
27
28 f("Hello");
29
30 i = 6;
31 f(", World");
32
33 function<void(const string&)> f2(f); // Create a 'std::function'.
34 i = 7;
35 f2("!");
36 }
37
38 // Prefer lambdas instead of bind.
39 void lambda()
40 {
41 // Swapping arguments.
42 const auto f = [](auto&& arg1, auto&& arg2)
43 {
44 // Perfect forwarding (not necessary).
45 print(forward<decltype(arg2)>(arg2), forward<decltype(arg1)>(arg1));
46 };
47
48 f("Hello", 42);
49 }
50 }
51
52 void Bind::tests()
53 {
54 Bind::bind();
55 cout << "-----" << endl;
56 Bind::lambda();
57 }