-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinit_capture.cpp
More file actions
71 lines (62 loc) · 1.61 KB
/
init_capture.cpp
File metadata and controls
71 lines (62 loc) · 1.61 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
#include <memory>
#include <vector>
#include <functional>
class Widget {
public:
bool IsValidated() const { return true; }
bool IsProcessed() const { return false; }
bool IsArchived() const { return true; }
};
auto pw = std::make_unique<Widget>();
// configure *pw
/* configure(*pw);*/
auto func = [pw = std::move(pw)] { // c++14, init capture
return pw->IsValidated() &&
pw->IsArchived();
};
// need not configure *pw
auto func2 = [pw = std::make_unique<Widget>()] {
return pw->IsValidated() &&
pw->IsArchived();
};
class IsValidatedAndArchived {
public:
using DataType = std::unique_ptr<Widget>;
explicit IsValidatedAndArchived(DataType&& ptr)
: pw(std::move(ptr)) {}
bool operator()() const {
return pw->IsValidated() && pw->IsArchived();
}
private:
DataType pw;
};
// c++11
auto func3 = IsValidatedAndArchived(std::make_unique<Widget>());
int main() {
std::vector<double> data;
auto func4 = [data = std::move(data)] { // c++14 init capture
/* use of data */
};
// c++11 emulation of init capture, works on g++, but not work on clang++
auto func5 = std::bind(
[](const std::vector<double>& data) {
/* use of data */
},
std::move(data)
);
// c++11 emulation of init capture for mutable lambda, works on g++, but not work on clang++
auto func6 = std::bind(
[](std::vector<double>& data) mutable {
/* use of data */
},
std::move(data)
);
// c++11 emulation
auto func7 = std::bind(
[](const std::unique_ptr<Widget>& pw) {
return pw->IsValidated() && pw->IsArchived();
},
std::make_unique<Widget>()
);
return 0;
}