C++闭包探索

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
#include<iostream>
using namespace std;
/*
* 利用c++类嵌套内部类实现闭包
*/
class ITest
{
public:
void operator() ()
{
process();
}

virtual ~ITest(){}
protected:
virtual void process() = 0;
};
ITest * test()
{
static int count = 0;
class Test: public ITest
{
public:
virtual void process()
{
cout << "嵌套内部类:" << " Count is " << count++ <<endl;
}
};

return new Test();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/*
* 利用函数内部类实现闭包
*/
typedef void (*Func)(const char *);

Func testFunc()
{
static int count = 100;

class Test
{
public:
static void process(const char * pName = NULL)
{
if(pName == NULL){
pName = "moses";
}
cout << "函数内部类:"<< pName << " Count is "<< count-- << endl;
}
};

return Test::process;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/*
* c++新特性lambda表达式实现闭包
*/
std::function<void(const char *)> lambdaTest()
{
int count = 100;

auto func = [count] (const char * pName = NULL) mutable {
if(pName == NULL){
pName = "moses";
}
cout << "lambda : " << pName << " Count is " << count-- << endl;
};

return func;
}