(三)使用bind生成类的成员函数的可调用对象

1. C++

  • std::function
  • std::bind
  • std::shared_ptr
  • std::vector

2. demo

#include <iostream>
#include <string>
#include <functional>
#include <memory>
#include <vector>
using namespace std;

class Info{
public:
    void SetName(const string &strName){
        name = strName;
    }
    string GetName(){
        return name;
    }

private:
    string name;
};

void bind_test()
{
    shared_ptr<Info> b = make_shared<Info>();
    b->SetName("jim");
    cout << b->GetName() << endl;

    vector<shared_ptr<Info>> vecInfo;
    function<string(void)> fn = bind(&Info::GetName, b);
    vecInfo.push_back(b);

    for (auto iter : vecInfo){
        cout << iter->GetName() << endl;
    }
}

int main()
{
    bind_test();
    return 0;
}

3. 用途

绑定的函数可用于观察者模式的被调用对象。

原文地址:https://www.cnblogs.com/walkinginthesun/p/9134230.html