zoukankan      html  css  js  c++  java
  • C++ Bind adapter usage

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


  • 相关阅读:
    期望
    更改开机默认操作系统及等待时间修改
    Python排序
    Python IDLE入门 + Python 电子书
    Python基础教程——1基础知识
    Java:谈谈protected访问权限
    三星I9100有时不能收发彩信完美解决!中国移动
    java继承的权限问题
    Python基础教程——2列表和元组
    访问控制和继承(Java)
  • 原文地址:https://www.cnblogs.com/rogerroddick/p/2963588.html
Copyright © 2011-2022 走看看