1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
| #include <functional>
class Test124 {
public:
int Sum(int x, int y) {
return x + y;
}
};
int main()
{
Test124 testObj;
// functional1 can be defined using 'auto' keyword instead
std::function<int(int, int)> functional1 = std::bind(&Test124::Sum, testObj,
std::placeholders::_1, std::placeholders::_2);
int result1 = functional1(1, 2);
// functional2 can not be defined using 'auto' keyword instead
std::function<int(Test124, int, int)> functional2 = &Test124::Sum;
int result2 = functional2(testObj, 1, 2);
return 1;
} |
#include <functional>
class Test124 {
public:
int Sum(int x, int y) {
return x + y;
}
};
int main()
{
Test124 testObj;
// functional1 can be defined using 'auto' keyword instead
std::function<int(int, int)> functional1 = std::bind(&Test124::Sum, testObj,
std::placeholders::_1, std::placeholders::_2);
int result1 = functional1(1, 2);
// functional2 can not be defined using 'auto' keyword instead
std::function<int(Test124, int, int)> functional2 = &Test124::Sum;
int result2 = functional2(testObj, 1, 2);
return 1;
}
ON_SCOPE_GUARD
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
| class ScopeExit {
public:
ScopeExit() = default;
ScopeExit(const ScopeExit&) = delete;
void operator=(const ScopeExit&) = delete;
ScopeExit(ScopeExit&&) = default;
ScopeExit& operator=(ScopeExit&&) = default;
template <typename F, typename... Args>
ScopeExit(F&& f, Args&&... args) {
func_ = std::bind(std::forward<F>(f), std::forward<Args>(args)...);
}
~ScopeExit() {
if (func_) {
func_();
}
};
private:
std::function<void()> func_;
};
#define _SCOPE_CONCAT(a, b) a##b
#define _SCOPE_MAKE_SCOPE_(line) ScopeExit _SCOPE_CONCAT(defer, line) = [&]()
#undef ON_SCOPE_GUARD
#define ON_SCOPE_GUARD _SCOPE_MAKE_SCOPE_(__LINE__)
int main()
{
FILE* fp = fopen("d:/aa.txt", "w+");
ON_SCOPE_GUARD {
fclose(fp);
};
fprintf(fp, "hello, file system.\n");
return 1;
} |
class ScopeExit {
public:
ScopeExit() = default;
ScopeExit(const ScopeExit&) = delete;
void operator=(const ScopeExit&) = delete;
ScopeExit(ScopeExit&&) = default;
ScopeExit& operator=(ScopeExit&&) = default;
template <typename F, typename... Args>
ScopeExit(F&& f, Args&&... args) {
func_ = std::bind(std::forward<F>(f), std::forward<Args>(args)...);
}
~ScopeExit() {
if (func_) {
func_();
}
};
private:
std::function<void()> func_;
};
#define _SCOPE_CONCAT(a, b) a##b
#define _SCOPE_MAKE_SCOPE_(line) ScopeExit _SCOPE_CONCAT(defer, line) = [&]()
#undef ON_SCOPE_GUARD
#define ON_SCOPE_GUARD _SCOPE_MAKE_SCOPE_(__LINE__)
int main()
{
FILE* fp = fopen("d:/aa.txt", "w+");
ON_SCOPE_GUARD {
fclose(fp);
};
fprintf(fp, "hello, file system.\n");
return 1;
}