#include "stdafx.h"
#include <iostream>
#include <functional>
using namespace std;
std::function<int(void)> func;
int testFunc()
{
cout << "global Func" << endl;
return 0;
}
auto lambda = [](void) -> int {cout << "lambda func" << endl; return 0; };
class Func
{
int operator()(void)
{
cout << "仿函数" << endl;
return 0;
}
};
class CFuntion
{
public:
int ClassMember() { cout << "class member function" << endl; return 0; }
int static StaticClassFunc() { cout << "static class member function" << endl; return 0; }
};
int main()
{
func = testFunc;
func();
func = lambda;
func();
func = CFuntion::StaticClassFunc;
func();
CFuntion classFunc;
func = std::bind(&CFuntion::ClassMember, classFunc); //bind非静态成员函数
func();
return 0;
}
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
static int cnt = 0;
void f(const char *p)
{
cout << ++cnt << ": ";
cout << p << endl;
}
void f1(int i)
{
cout<<i<<endl;
}
int main()
{
vector<const char*> v;
v.push_back("hello");
v.push_back("world");
//vector<const char*>::iterator it;
for_each(v.begin(), v.end(), &f);
vector<int> v1={1,2,3,4};
for_each(v1.begin(),v1.end(),f1);
return 0;
}
bind2nd在类的非静态成员函数使用的时候,要注意到每个非静态成员函数都隐含着this
指针,这也意味着在参数列表中的第一个参数始终是this
。
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
using namespace std;
class AbstractDoor {
public:
virtual void open(const char *str)const = 0;
virtual ~AbstractDoor() { cout << "~AbstractDoor()" << endl; }
};
class HorizontalDoor :public AbstractDoor {
public:
void open(const char *str)const
{
cout << str << "HorizontalDoor" << endl;
}
};
class VerticalDoor :public AbstractDoor {
public:
void open(const char *str)const
{
cout << str << "VerticalDoor" << endl;
}
};
class DoorController {
protected:
vector<AbstractDoor *> _doorVec;
public:
void addDoor(AbstractDoor *door) {
_doorVec.push_back(door);
}
void openDoor()const {
for_each(_doorVec.begin(), _doorVec.end(), bind2nd(mem_fun(&AbstractDoor::open),"John: "));
}
~DoorController() {
for_each(_doorVec.begin(), _doorVec.end(), [](AbstractDoor *p) {
delete p;
p = nullptr;
});
}
};
int main()
{
DoorController dc;
dc.addDoor(new VerticalDoor());
dc.addDoor(new HorizontalDoor);
dc.addDoor(new VerticalDoor);
dc.openDoor();
return 0;
}