function wrap

This post will introduce a C++ 11 feature, std::function. It can wrap any kind of callable element into a copyable object and whose type depands soly on its call signature.

std::function is an object who can replace the function poiner in C language but more safety. It is useful for implement of many C++ design patterns.

std::function
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
#include <cstdlib>
#include <functional>
#include <vector>
typedef std::function<int(int,int)> IntOpFun;
struct Adder {
int OnAB(int iA, int iB) {
printf("Add(%d,%d)=%d", iA, iB, iA + iB);
return iA + iB;
}
};
struct Muler {
int OnAB(int iA, int iB) {
printf("Mul3(%d,%d)=%d", iA, iB, iA * iB);
return iA * iB;
}
};
struct Subject {
void AddObserver(IntOpFun of) {
m_vecOf.push_back(of);
}
void Notify(int iA, int iB) {
for (auto iter = m_vecOf.begin(); iter != m_vecOf.end(); ++iter) {
(*iter)(iA, iB);
}
}
std::vector<IntOpFun> m_vecOf;
};
int main() {
Subject3 subj;
Adder3 adder;
Muler3 muler;
subj.AddObserver(std::bind(&Adder3::OnAB, &adder, std::placeholders::_1, std::placeholders::_2));
subj.AddObserver(std::bind(&Muler3::OnAB, &muler, std::placeholders::_1, std::placeholders::_2));
subj.Notify(1, 2);
return 0;
}