Roger Luo

超越梦想一起飞
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

C++ Bind adapter usage

Posted on 2013-03-16 17:30  Roger Luo  阅读(339)  评论(0编辑  收藏  举报

bind function adapter (included <functional>)

Introduce:

bind(op, args, …)  Binds args to op

Simple Code

auto pfn = std::bind(std::plus<int>(), std::placeholders::_1, 10);
cout<<pfn(7); // 17

Note that bind() internally copies passed arguments. To let the function object use a reference to a passed argument, use ref() or cref()

void Increment(int& i) {i++;}
...
// ref function
auto prf = bind(Increment, _1);
int i = 1;
prf(i);
cout<<i<<endl;// 2

For member function
class BindTest
{
public:
int AddM(int lhs, int rhs) const {return lhs + rhs;}
};
class BindPerson
{
public:
BindPerson(const string& name):_name(name){}
void Print() const {cout<<_name<<endl;}
private:
string _name;
};

int main()
{
// member function
BindTest _bt1;
auto pmf = bind(&BindTest::AddM, _1, _2, _3);
cout<<pmf(_bt1, 1, 3)<<endl;//cout<<bind(&BindTest::AddM, _1, _2, _3)(_bt1, 1, 3)<<endl;

vector<BindPerson> vp = {BindPerson("A1"), BindPerson("A2"), BindPerson("A3")};
for_each(vp.begin(), vp.end(), bind(&BindPerson::Print, _1));
return 0;
}
Note: the member funciton should be const function.
Note that you can also pass pointers to objects and even smart pointers to bind():
vector<BindPerson*> vpp = {new BindPerson("B1"), new BindPerson("B2"), new BindPerson("B3")};
for_each(vpp.begin(), vpp.end(), bind(&BindPerson::Print, _1));
for(auto elem : vpp)
{
delete elem;
elem = nullptr;
}

vector<shared_ptr<BindPerson>> vps = {make_shared<BindPerson>("C1"), make_shared<BindPerson>("C2")};
for_each(vps.begin(), vps.end(), bind(&BindPerson::Print, _1));