주의할 점은 std::function을 함수의 인자로 넘길 때
const를 붙여야 한다.
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 <functional>
class FunctionObj
{
public:
void operator() (int i)
{
std::cout << "functionObj" << i << std::endl;
}
};
void freeFunction(int i)
{
std::cout << "freeFunction" << i << std::endl;
}
// 함수 포인터 전달
void runFunction(int i, void (*fnPtr)(int))
{
(*fnPtr)(i);
}
// std::functional 사용
void runFunction_functional(int i, const std::function<void(int)>& fn)
{
fn(i);
}
void runFunctions_vector(const std::vector<std::function<void(int)>> functions)
{
int i = 0;
for (const auto& fn : functions)
{
fn(++i);
}
}
int main()
{
freeFunction(10);
// Function Pointer
void(*fnPtr)(int);
fnPtr = freeFunction;
//(*fnPtr)(20);
//runFunction(10, fnPtr);
runFunction_functional(20, fnPtr);
FunctionObj functionObj;
functionObj(10);
auto lambdaFn = [](int i)
{
std::cout << "lambdaFunction" << i << std::endl;
};
//lambdaFn(10);
runFunction(10, lambdaFn);
std::vector<std::function<void(int)>> functions;
functions.emplace_back(freeFunction);
functions.emplace_back(functionObj);
functions.emplace_back(lambdaFn);
runFunctions_vector(functions);
}
|
'C' 카테고리의 다른 글
vector time complexity, emplace_back 정리 (0) | 2021.06.25 |
---|---|
c++ vector basic 설명 (0) | 2021.06.25 |
c++ lambda + stl(filter, sort, remove_if, reduce, vector) (0) | 2021.06.24 |
c++ lambda expression, capture =, & (0) | 2021.06.23 |
c++ weak pointer 정리 (0) | 2021.06.23 |