-
Notifications
You must be signed in to change notification settings - Fork 1
/
item32_use_init_capture.cpp
68 lines (59 loc) · 1.58 KB
/
item32_use_init_capture.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
#include <iostream>
#include "type_name.hpp"
#include <functional>
using namespace std;
/* C++14 supports the method to move object to closure */
class Widget{
public:
bool isValidated() const;
bool isProcessed() const;
bool isArchived() const;
private:
};
bool Widget::isArchived() const{
return false;
}
bool Widget::isProcessed() const{
return false;
}
bool Widget::isValidated() const{
return true;
}
/* Writen in c++11 */
class IsValAndArch{
public:
using DataType = std::unique_ptr<Widget>;
explicit IsValAndArch(DataType&& ptr):
pw(std::move(ptr)){}
bool operator()() const{
cout << "Invoke operator() ";
return pw->isArchived() && pw->isProcessed();
}
private:
DataType pw;
};
int main(){
auto pw = make_unique<Widget>();
auto func = [pw = std::move(pw)]{
cout << "pw's type :" << type_name<decltype(pw)>() << endl;
return pw->isArchived() && pw->isProcessed();
};
cout << boolalpha << "func: "<< func() << endl;
/* More concise */
auto func1 = [pw = make_unique<Widget>()]{
return pw->isArchived() && pw->isValidated();
};
cout << "func1: " << func1() << endl;
/* Test on c++11 version */
auto func2 = IsValAndArch(std::make_unique<Widget>());
//func2();
cout << "func2: " << func2() << endl;
/* C++11 emulation */
auto func3 = std::bind(
[](const std::unique_ptr<Widget>& pw){
return pw->isArchived() && pw->isProcessed(); },
std::make_unique<Widget>()
);
cout << "func3: " << func3() << endl;
return 0;
}