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));