TheRiver | blog

You have reached the world's edge, none but devils play past here

0%

function bind

reference

http://blog.bitfoc.us/p/525

STL 源码简析 – std::function

Naive std::function implementation

step1 匹配函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
using namespace std;

template <typename T>
struct function{};

template <typename ret, typename lhs, typename rhs>
struct function<ret(lhs, rhs)>
{
enum {values = 2};
};

int func(int, int)
{
cout << "func ..." << endl;
}

int main()
{
cout << function<int(int, int)>::values << endl; //2
}

step2 模板匹配分析

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
#include <iostream>
using namespace std;

template <typename T>
struct function{};

template <typename ret, typename lhs, typename rhs>
struct function<ret(lhs, rhs)>
{
static const int values1 = std::is_same<int, ret>();
static const int values2 = std::is_same<int, lhs>();
static const int values3 = std::is_same<int, rhs>();
};

int func(int, int)
{
cout << "func ..." << endl;
}

int main()
{
cout << function<int(int, int)>::values1 << endl; //1
cout << function<int(int, int)>::values2 << endl; //1
cout << function<int(int, int)>::values3 << endl; //1

cout << function<double(int, int)>::values1 << endl; //0
cout << function<int(double, int)>::values2 << endl; //0
cout << function<int(int, double)>::values3 << endl; //0
}

step3 运行函数

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
#include <iostream>
using namespace std;

template <typename T>
struct function{};

template <typename ret, typename lhs, typename rhs>
struct function<ret(lhs, rhs)>
{
using functype = ret (*)(lhs, rhs);
functype callfunc;

template<typename T>
function(T param):callfunc(param){

}

ret operator()(lhs l, rhs r){ //函数调用运算符
return callfunc(l, r);
}
};

int func(int lhs, int rhs)
{
cout << "func ..." << endl;
cout << lhs + rhs << endl;
}

int main()
{
function<int(int, int)> test = &func;
test(1, 2);
}

ending

2020071603.jpg

----------- ending -----------