当前位置: 代码迷 >> 综合 >> 【C++11】std::function和std::bind
  详细解决方案

【C++11】std::function和std::bind

热度:15   发布时间:2024-01-19 06:42:55.0

std::function + std::bind,可以将所有函数都能统一到 std::function。
在应用中,可以优雅的将类成员函数使用到诸如回调,线程函数等场合。
举例:

#include <thread>
#include <functional>using std::placeholders::_1;
using std::placeholders::_2;class Test
{// ...
public:int add(const int a, const int b){return a+b;}
}//
int main()
{Test t;std::function< int(int, int) > pfun = std::bind(&Test::add, &t, _1, _2);//auto pfun = std::bind(&Test::add, &t, _1, _2);// 直接调用  pfun(2, 3); // 用于线程函数std::thread t(pfun, 4, 6); return 0;
}


 

  相关解决方案